8 * Class representing a MediaWiki article and history.
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
19 var $mComment = ''; // !<
21 var $mContentLoaded = false; // !<
22 var $mCounter = -1; // !< Not loaded
23 var $mCurID = -1; // !< Not loaded
24 var $mDataLoaded = false; // !<
25 var $mForUpdate = false; // !<
26 var $mGoodAdjustment = 0; // !<
27 var $mIsRedirect = false; // !<
28 var $mLatest = false; // !<
29 var $mMinorEdit; // !<
31 var $mPreparedEdit = false; // !< Title object if set
32 var $mRedirectedFrom = null; // !< Title object if set
33 var $mRedirectTarget = null; // !< Title object if set
34 var $mRedirectUrl = false; // !<
35 var $mRevIdFetched = 0; // !<
37 var $mTimestamp = ''; // !<
39 var $mTotalAdjustment = 0; // !<
40 var $mTouched = '19700101000000'; // !<
41 var $mUser = -1; // !< Not loaded
42 var $mUserText = ''; // !<
43 var $mParserOptions; // !<
44 var $mParserOutput; // !<
48 * Constructor and clear the article
49 * @param $title Reference to a Title object.
50 * @param $oldId Integer revision ID, null to fetch from request, zero for current
52 public function __construct( Title
$title, $oldId = null ) {
53 $this->mTitle
=& $title;
54 $this->mOldId
= $oldId;
58 * Constructor from an article article
59 * @param $id The article ID to load
61 public static function newFromID( $id ) {
62 $t = Title
::newFromID( $id );
63 # FIXME: doesn't inherit right
64 return $t == null ?
null : new self( $t );
65 # return $t == null ? null : new static( $t ); // PHP 5.3
69 * Tell the page view functions that this view was redirected
70 * from another page on the wiki.
71 * @param $from Title object.
73 public function setRedirectedFrom( Title
$from ) {
74 $this->mRedirectedFrom
= $from;
78 * If this page is a redirect, get its target
80 * The target will be fetched from the redirect table if possible.
81 * If this page doesn't have an entry there, call insertRedirect()
82 * @return mixed Title object, or null if this page is not a redirect
84 public function getRedirectTarget() {
85 if ( !$this->mTitle ||
!$this->mTitle
->isRedirect() )
87 if ( !is_null( $this->mRedirectTarget
) )
88 return $this->mRedirectTarget
;
89 # Query the redirect table
90 $dbr = wfGetDB( DB_SLAVE
);
91 $row = $dbr->selectRow( 'redirect',
92 array( 'rd_namespace', 'rd_title' ),
93 array( 'rd_from' => $this->getID() ),
97 return $this->mRedirectTarget
= Title
::makeTitle( $row->rd_namespace
, $row->rd_title
);
99 # This page doesn't have an entry in the redirect table
100 return $this->mRedirectTarget
= $this->insertRedirect();
104 * Insert an entry for this page into the redirect table.
106 * Don't call this function directly unless you know what you're doing.
107 * @return Title object
109 public function insertRedirect() {
110 $retval = Title
::newFromRedirect( $this->getContent() );
114 $dbw = wfGetDB( DB_MASTER
);
115 $dbw->replace( 'redirect', array( 'rd_from' ),
117 'rd_from' => $this->getID(),
118 'rd_namespace' => $retval->getNamespace(),
119 'rd_title' => $retval->getDBkey()
127 * Get the Title object this page redirects to
129 * @return mixed false, Title of in-wiki target, or string with URL
131 public function followRedirect() {
132 $text = $this->getContent();
133 return $this->followRedirectText( $text );
137 * Get the Title object this text redirects to
139 * @param $text string article content containing redirect info
140 * @return mixed false, Title of in-wiki target, or string with URL
142 public function followRedirectText( $text ) {
143 $rt = Title
::newFromRedirectRecurse( $text ); // recurse through to only get the final target
144 # process if title object is valid and not special:userlogout
146 if ( $rt->getInterwiki() != '' ) {
147 if ( $rt->isLocal() ) {
148 // Offsite wikis need an HTTP redirect.
150 // This can be hard to reverse and may produce loops,
151 // so they may be disabled in the site configuration.
152 $source = $this->mTitle
->getFullURL( 'redirect=no' );
153 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
156 if ( $rt->getNamespace() == NS_SPECIAL
) {
157 // Gotta handle redirects to special pages differently:
158 // Fill the HTTP response "Location" header and ignore
159 // the rest of the page we're on.
161 // This can be hard to reverse, so they may be disabled.
162 if ( $rt->isSpecial( 'Userlogout' ) ) {
165 return $rt->getFullURL();
171 // No or invalid redirect
176 * get the title object of the article
177 * @return Title object of current title
179 public function getTitle() {
180 return $this->mTitle
;
187 public function clear() {
188 $this->mDataLoaded
= false;
189 $this->mContentLoaded
= false;
191 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
192 $this->mRedirectedFrom
= null; # Title object if set
193 $this->mRedirectTarget
= null; # Title object if set
195 $this->mTimestamp
= $this->mComment
= '';
196 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
197 $this->mTouched
= '19700101000000';
198 $this->mForUpdate
= false;
199 $this->mIsRedirect
= false;
200 $this->mRevIdFetched
= 0;
201 $this->mRedirectUrl
= false;
202 $this->mLatest
= false;
203 $this->mPreparedEdit
= false;
207 * Note that getContent/loadContent do not follow redirects anymore.
208 * If you need to fetch redirectable content easily, try
209 * the shortcut in Article::followContent()
211 * @return Return the text of this revision
213 public function getContent() {
214 global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
215 wfProfileIn( __METHOD__
);
216 if ( $this->getID() === 0 ) {
217 # If this is a MediaWiki:x message, then load the messages
218 # and return the message value for x.
219 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
220 # If this is a system message, get the default text.
221 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle
->getText() ) );
222 $wgMessageCache->loadAllMessages( $lang );
223 $text = wfMsgGetKey( $message, false, $lang, false );
224 if ( wfEmptyMsg( $message, $text ) )
227 $text = wfMsgExt( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon', 'parsemag' );
229 wfProfileOut( __METHOD__
);
232 $this->loadContent();
233 wfProfileOut( __METHOD__
);
234 return $this->mContent
;
239 * Get the text of the current revision. No side-effects...
241 * @return Return the text of the current revision
243 public function getRawText() {
244 // Check process cache for current revision
245 if ( $this->mContentLoaded
&& $this->mOldId
== 0 ) {
246 return $this->mContent
;
248 $rev = Revision
::newFromTitle( $this->mTitle
);
249 $text = $rev ?
$rev->getRawText() : false;
254 * This function returns the text of a section, specified by a number ($section).
255 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
256 * the first section before any such heading (section 0).
258 * If a section contains subsections, these are also returned.
260 * @param $text String: text to look in
261 * @param $section Integer: section number
262 * @return string text of the requested section
265 public function getSection( $text, $section ) {
267 return $wgParser->getSection( $text, $section );
271 * Get the text that needs to be saved in order to undo all revisions
272 * between $undo and $undoafter. Revisions must belong to the same page,
273 * must exist and must not be deleted
274 * @param $undo Revision
275 * @param $undoafter Revision Must be an earlier revision than $undo
276 * @return mixed string on success, false on failure
278 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
279 $undo_text = $undo->getText();
280 $undoafter_text = $undoafter->getText();
281 $cur_text = $this->getContent();
282 if ( $cur_text == $undo_text ) {
283 # No use doing a merge if it's just a straight revert.
284 return $undoafter_text;
287 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) )
293 * @return int The oldid of the article that is to be shown, 0 for the
296 public function getOldID() {
297 if ( is_null( $this->mOldId
) ) {
298 $this->mOldId
= $this->getOldIDFromRequest();
300 return $this->mOldId
;
304 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
306 * @return int The old id for the request
308 public function getOldIDFromRequest() {
310 $this->mRedirectUrl
= false;
311 $oldid = $wgRequest->getVal( 'oldid' );
312 if ( isset( $oldid ) ) {
313 $oldid = intval( $oldid );
314 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
315 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
319 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
321 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
322 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
335 * Load the revision (including text) into this object
337 function loadContent() {
338 if ( $this->mContentLoaded
) return;
339 wfProfileIn( __METHOD__
);
341 $oldid = $this->getOldID();
342 # Pre-fill content with error message so that if something
343 # fails we'll have something telling us what we intended.
344 $this->mOldId
= $oldid;
345 $this->fetchContent( $oldid );
346 wfProfileOut( __METHOD__
);
351 * Fetch a page record with the given conditions
352 * @param $dbr Database object
353 * @param $conditions Array
354 * @return mixed Database result resource, or false on failure
356 protected function pageData( $dbr, $conditions ) {
370 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
371 $row = $dbr->selectRow(
377 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
382 * Fetch a page record matching the Title object's namespace and title
383 * using a sanitized title string
385 * @param $dbr Database object
386 * @param $title Title object
387 * @return mixed Database result resource, or false on failure
389 public function pageDataFromTitle( $dbr, $title ) {
390 return $this->pageData( $dbr, array(
391 'page_namespace' => $title->getNamespace(),
392 'page_title' => $title->getDBkey() ) );
396 * Fetch a page record matching the requested ID
398 * @param $dbr Database
401 protected function pageDataFromId( $dbr, $id ) {
402 return $this->pageData( $dbr, array( 'page_id' => $id ) );
406 * Set the general counter, title etc data loaded from
409 * @param $data Database row object or "fromdb"
411 public function loadPageData( $data = 'fromdb' ) {
412 if ( $data === 'fromdb' ) {
413 $dbr = wfGetDB( DB_MASTER
);
414 $data = $this->pageDataFromId( $dbr, $this->getId() );
417 $lc = LinkCache
::singleton();
419 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
);
421 $this->mTitle
->mArticleID
= intval( $data->page_id
);
423 # Old-fashioned restrictions
424 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
426 $this->mCounter
= intval( $data->page_counter
);
427 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
428 $this->mIsRedirect
= intval( $data->page_is_redirect
);
429 $this->mLatest
= intval( $data->page_latest
);
431 if ( is_object( $this->mTitle
) ) {
432 $lc->addBadLinkObj( $this->mTitle
);
434 $this->mTitle
->mArticleID
= 0;
437 $this->mDataLoaded
= true;
441 * Get text of an article from database
442 * Does *NOT* follow redirects.
444 * @param $oldid Int: 0 for whatever the latest revision is
445 * @return mixed string containing article contents, or false if null
447 function fetchContent( $oldid = 0 ) {
448 if ( $this->mContentLoaded
) {
449 return $this->mContent
;
452 $dbr = wfGetDB( DB_MASTER
);
454 # Pre-fill content with error message so that if something
455 # fails we'll have something telling us what we intended.
456 $t = $this->mTitle
->getPrefixedText();
457 $d = $oldid ?
wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
458 $this->mContent
= wfMsgNoTrans( 'missing-article', $t, $d ) ;
461 $revision = Revision
::newFromId( $oldid );
462 if ( is_null( $revision ) ) {
463 wfDebug( __METHOD__
. " failed to retrieve specified revision, id $oldid\n" );
466 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
468 wfDebug( __METHOD__
. " failed to get page data linked to revision id $oldid\n" );
471 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
472 $this->loadPageData( $data );
474 if ( !$this->mDataLoaded
) {
475 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
477 wfDebug( __METHOD__
. " failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
480 $this->loadPageData( $data );
482 $revision = Revision
::newFromId( $this->mLatest
);
483 if ( is_null( $revision ) ) {
484 wfDebug( __METHOD__
. " failed to retrieve current page, rev_id {$this->mLatest}\n" );
489 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
490 // We should instead work with the Revision object when we need it...
491 $this->mContent
= $revision->getText( Revision
::FOR_THIS_USER
); // Loads if user is allowed
493 $this->mUser
= $revision->getUser();
494 $this->mUserText
= $revision->getUserText();
495 $this->mComment
= $revision->getComment();
496 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
498 $this->mRevIdFetched
= $revision->getId();
499 $this->mContentLoaded
= true;
500 $this->mRevision
=& $revision;
502 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
504 return $this->mContent
;
508 * Read/write accessor to select FOR UPDATE
510 * @param $x Mixed: FIXME
513 public function forUpdate( $x = null ) {
514 return wfSetVar( $this->mForUpdate
, $x );
518 * Get the database which should be used for reads
521 * @deprecated - just call wfGetDB( DB_MASTER ) instead
524 wfDeprecated( __METHOD__
);
525 return wfGetDB( DB_MASTER
);
529 * Get options for all SELECT statements
531 * @param $options Array: an optional options array which'll be appended to
533 * @return Array: options
535 protected function getSelectOptions( $options = '' ) {
536 if ( $this->mForUpdate
) {
537 if ( is_array( $options ) ) {
538 $options[] = 'FOR UPDATE';
540 $options = 'FOR UPDATE';
547 * @return int Page ID
549 public function getID() {
550 if ( $this->mTitle
) {
551 return $this->mTitle
->getArticleID();
558 * @return bool Whether or not the page exists in the database
560 public function exists() {
561 return $this->getId() > 0;
565 * Check if this page is something we're going to be showing
566 * some sort of sensible content for. If we return false, page
567 * views (plain action=view) will return an HTTP 404 response,
568 * so spiders and robots can know they're following a bad link.
572 public function hasViewableContent() {
573 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
577 * @return int The view count for the page
579 public function getCount() {
580 if ( -1 == $this->mCounter
) {
581 $id = $this->getID();
585 $dbr = wfGetDB( DB_SLAVE
);
586 $this->mCounter
= $dbr->selectField( 'page',
588 array( 'page_id' => $id ),
590 $this->getSelectOptions()
594 return $this->mCounter
;
598 * Determine whether a page would be suitable for being counted as an
599 * article in the site_stats table based on the title & its content
601 * @param $text String: text to analyze
604 public function isCountable( $text ) {
605 global $wgUseCommaCount;
607 $token = $wgUseCommaCount ?
',' : '[[';
608 return $this->mTitle
->isContentPage() && !$this->isRedirect( $text ) && in_string( $token, $text );
612 * Tests if the article text represents a redirect
614 * @param $text String: FIXME
617 public function isRedirect( $text = false ) {
618 if ( $text === false ) {
619 if ( $this->mDataLoaded
) {
620 return $this->mIsRedirect
;
622 // Apparently loadPageData was never called
623 $this->loadContent();
624 $titleObj = Title
::newFromRedirectRecurse( $this->fetchContent() );
626 $titleObj = Title
::newFromRedirect( $text );
628 return $titleObj !== null;
632 * Returns true if the currently-referenced revision is the current edit
633 * to this page (and it exists).
636 public function isCurrent() {
637 # If no oldid, this is the current version.
638 if ( $this->getOldID() == 0 ) {
641 return $this->exists() && isset( $this->mRevision
) && $this->mRevision
->isCurrent();
645 * Loads everything except the text
646 * This isn't necessary for all uses, so it's only done if needed.
648 protected function loadLastEdit() {
649 if ( -1 != $this->mUser
)
652 # New or non-existent articles have no user information
653 $id = $this->getID();
654 if ( 0 == $id ) return;
656 $this->mLastRevision
= Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
657 if ( !is_null( $this->mLastRevision
) ) {
658 $this->mUser
= $this->mLastRevision
->getUser();
659 $this->mUserText
= $this->mLastRevision
->getUserText();
660 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
661 $this->mComment
= $this->mLastRevision
->getComment();
662 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
663 $this->mRevIdFetched
= $this->mLastRevision
->getId();
667 public function getTimestamp() {
668 // Check if the field has been filled by ParserCache::get()
669 if ( !$this->mTimestamp
) {
670 $this->loadLastEdit();
672 return wfTimestamp( TS_MW
, $this->mTimestamp
);
675 public function getUser() {
676 $this->loadLastEdit();
680 public function getUserText() {
681 $this->loadLastEdit();
682 return $this->mUserText
;
685 public function getComment() {
686 $this->loadLastEdit();
687 return $this->mComment
;
690 public function getMinorEdit() {
691 $this->loadLastEdit();
692 return $this->mMinorEdit
;
695 /* Use this to fetch the rev ID used on page views */
696 public function getRevIdFetched() {
697 $this->loadLastEdit();
698 return $this->mRevIdFetched
;
702 * @param $limit Integer: default 0.
703 * @param $offset Integer: default 0.
705 public function getContributors( $limit = 0, $offset = 0 ) {
706 # XXX: this is expensive; cache this info somewhere.
708 $dbr = wfGetDB( DB_SLAVE
);
709 $revTable = $dbr->tableName( 'revision' );
710 $userTable = $dbr->tableName( 'user' );
712 $pageId = $this->getId();
714 $user = $this->getUser();
716 $excludeCond = "AND rev_user != $user";
718 $userText = $dbr->addQuotes( $this->getUserText() );
719 $excludeCond = "AND rev_user_text != $userText";
722 $deletedBit = $dbr->bitAnd( 'rev_deleted', Revision
::DELETED_USER
); // username hidden?
724 $sql = "SELECT {$userTable}.*, rev_user_text as user_name, MAX(rev_timestamp) as timestamp
725 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
726 WHERE rev_page = $pageId
729 GROUP BY rev_user, rev_user_text
730 ORDER BY timestamp DESC";
733 $sql = $dbr->limitResult( $sql, $limit, $offset );
735 $sql .= ' ' . $this->getSelectOptions();
736 $res = $dbr->query( $sql, __METHOD__
);
738 return new UserArrayFromResult( $res );
742 * This is the default action of the index.php entry point: just view the
743 * page of the given title.
745 public function view() {
746 global $wgUser, $wgOut, $wgRequest, $wgContLang;
747 global $wgEnableParserCache, $wgStylePath, $wgParser;
748 global $wgUseTrackbacks, $wgUseFileCache;
750 wfProfileIn( __METHOD__
);
752 # Get variables from query string
753 $oldid = $this->getOldID();
754 $parserCache = ParserCache
::singleton();
756 $parserOptions = clone $this->getParserOptions();
757 # Render printable version, use printable version cache
758 if ( $wgOut->isPrintable() ) {
759 $parserOptions->setIsPrintable( true );
762 # Try client and file cache
763 if ( $oldid === 0 && $this->checkTouched() ) {
766 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
768 # Is is client cached?
769 if ( $wgOut->checkLastModified( $this->getTouched() ) ) {
770 wfDebug( __METHOD__
. ": done 304\n" );
771 wfProfileOut( __METHOD__
);
774 } else if ( $wgUseFileCache && $this->tryFileCache() ) {
775 wfDebug( __METHOD__
. ": done file cache\n" );
776 # tell wgOut that output is taken care of
778 $this->viewUpdates();
779 wfProfileOut( __METHOD__
);
784 $sk = $wgUser->getSkin();
786 # getOldID may want us to redirect somewhere else
787 if ( $this->mRedirectUrl
) {
788 $wgOut->redirect( $this->mRedirectUrl
);
789 wfDebug( __METHOD__
. ": redirecting due to oldid\n" );
790 wfProfileOut( __METHOD__
);
794 $wgOut->setArticleFlag( true );
795 # Set page title (may be overridden by DISPLAYTITLE)
796 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
798 # If we got diff in the query, we want to see a diff page instead of the article.
799 if ( !is_null( $wgRequest->getVal( 'diff' ) ) ) {
800 wfDebug( __METHOD__
. ": showing diff page\n" );
801 $this->showDiffPage();
802 wfProfileOut( __METHOD__
);
806 # Should the parser cache be used?
807 $useParserCache = $this->useParserCache( $oldid );
808 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
809 if ( $wgUser->getOption( 'stubthreshold' ) ) {
810 wfIncrStats( 'pcache_miss_stub' );
813 # For the main page, overwrite the <title> element with the con-
814 # tents of 'pagetitle-view-mainpage' instead of the default (if
816 if ( $this->mTitle
->equals( Title
::newMainPage() )
817 && ( $m = wfMsgForContent( 'pagetitle-view-mainpage' ) ) !== '' )
819 $wgOut->setHTMLTitle( $m );
822 $wasRedirected = $this->showRedirectedFromHeader();
823 $this->showNamespaceHeader();
825 # Iterate through the possible ways of constructing the output text.
826 # Keep going until $outputDone is set, or we run out of things to do.
829 while ( !$outputDone && ++
$pass ) {
832 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
836 # Try the parser cache
837 if ( $useParserCache ) {
838 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
839 if ( $this->mParserOutput
!== false ) {
840 wfDebug( __METHOD__
. ": showing parser cache contents\n" );
841 $wgOut->addParserOutput( $this->mParserOutput
);
842 # Ensure that UI elements requiring revision ID have
843 # the correct version information.
844 $wgOut->setRevisionId( $this->mLatest
);
851 $text = $this->getContent();
852 if ( $text === false ||
$this->getID() == 0 ) {
853 wfDebug( __METHOD__
. ": showing missing article\n" );
854 $this->showMissingArticle();
855 wfProfileOut( __METHOD__
);
859 # Another whitelist check in case oldid is altering the title
860 if ( !$this->mTitle
->userCanRead() ) {
861 wfDebug( __METHOD__
. ": denied on secondary read check\n" );
862 $wgOut->loginToUse();
865 wfProfileOut( __METHOD__
);
869 # Are we looking at an old revision
870 if ( $oldid && !is_null( $this->mRevision
) ) {
871 $this->setOldSubtitle( $oldid );
872 if ( !$this->showDeletedRevisionHeader() ) {
873 wfDebug( __METHOD__
. ": cannot view deleted revision\n" );
874 wfProfileOut( __METHOD__
);
877 # If this "old" version is the current, then try the parser cache...
878 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
879 $this->mParserOutput
= $parserCache->get( $this, $parserOptions );
880 if ( $this->mParserOutput
) {
881 wfDebug( __METHOD__
. ": showing parser cache for current rev permalink\n" );
882 $wgOut->addParserOutput( $this->mParserOutput
);
883 $wgOut->setRevisionId( $this->mLatest
);
884 $this->showViewFooter();
885 $this->viewUpdates();
886 wfProfileOut( __METHOD__
);
892 # Ensure that UI elements requiring revision ID have
893 # the correct version information.
894 $wgOut->setRevisionId( $this->getRevIdFetched() );
896 # Pages containing custom CSS or JavaScript get special treatment
897 if ( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
898 wfDebug( __METHOD__
. ": showing CSS/JS source\n" );
899 $this->showCssOrJsPage();
901 } else if ( $rt = Title
::newFromRedirectArray( $text ) ) {
902 wfDebug( __METHOD__
. ": showing redirect=no page\n" );
903 # Viewing a redirect page (e.g. with parameter redirect=no)
904 # Don't append the subtitle if this was an old revision
905 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
906 # Parse just to get categories, displaytitle, etc.
907 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
, $parserOptions );
908 $wgOut->addParserOutputNoText( $this->mParserOutput
);
914 # Run the parse, protected by a pool counter
915 wfDebug( __METHOD__
. ": doing uncached parse\n" );
916 $key = $parserCache->getKey( $this, $parserOptions );
917 $poolCounter = PoolCounter
::factory( 'Article::view', $key );
918 $dirtyCallback = $useParserCache ?
array( $this, 'tryDirtyCache' ) : false;
919 $status = $poolCounter->executeProtected( array( $this, 'doViewParse' ), $dirtyCallback );
921 if ( !$status->isOK() ) {
922 # Connection or timeout error
923 $this->showPoolError( $status );
924 wfProfileOut( __METHOD__
);
931 # Should be unreachable, but just in case...
937 # Now that we've filled $this->mParserOutput, we know whether
938 # there are any __NOINDEX__ tags on the page
939 $policy = $this->getRobotPolicy( 'view' );
940 $wgOut->setIndexPolicy( $policy['index'] );
941 $wgOut->setFollowPolicy( $policy['follow'] );
943 $this->showViewFooter();
944 $this->viewUpdates();
945 wfProfileOut( __METHOD__
);
949 * Show a diff page according to current request variables. For use within
950 * Article::view() only, other callers should use the DifferenceEngine class.
952 public function showDiffPage() {
953 global $wgOut, $wgRequest, $wgUser;
955 $diff = $wgRequest->getVal( 'diff' );
956 $rcid = $wgRequest->getVal( 'rcid' );
957 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
958 $purge = $wgRequest->getVal( 'action' ) == 'purge';
959 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
960 $oldid = $this->getOldID();
962 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge, $unhide );
963 // DifferenceEngine directly fetched the revision:
964 $this->mRevIdFetched
= $de->mNewid
;
965 $de->showDiffPage( $diffOnly );
967 // Needed to get the page's current revision
968 $this->loadPageData();
969 if ( $diff == 0 ||
$diff == $this->mLatest
) {
970 # Run view updates for current revision only
971 $this->viewUpdates();
976 * Show a page view for a page formatted as CSS or JavaScript. To be called by
977 * Article::view() only.
979 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
982 public function showCssOrJsPage() {
984 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
985 // Give hooks a chance to customise the output
986 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
987 // Wrap the whole lot in a <pre> and don't parse
989 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
990 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
991 $wgOut->addHTML( htmlspecialchars( $this->mContent
) );
992 $wgOut->addHTML( "\n</pre>\n" );
997 * Get the robot policy to be used for the current action=view request.
998 * @return String the policy that should be set
999 * @deprecated use getRobotPolicy() instead, which returns an associative
1002 public function getRobotPolicyForView() {
1003 wfDeprecated( __FUNC__
);
1004 $policy = $this->getRobotPolicy( 'view' );
1005 return $policy['index'] . ',' . $policy['follow'];
1009 * Get the robot policy to be used for the current view
1010 * @param $action String the action= GET parameter
1011 * @return Array the policy that should be set
1012 * TODO: actions other than 'view'
1014 public function getRobotPolicy( $action ) {
1016 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
1017 global $wgDefaultRobotPolicy, $wgRequest;
1019 $ns = $this->mTitle
->getNamespace();
1020 if ( $ns == NS_USER ||
$ns == NS_USER_TALK
) {
1021 # Don't index user and user talk pages for blocked users (bug 11443)
1022 if ( !$this->mTitle
->isSubpage() ) {
1023 $block = new Block();
1024 if ( $block->load( $this->mTitle
->getText() ) ) {
1025 return array( 'index' => 'noindex',
1026 'follow' => 'nofollow' );
1031 if ( $this->getID() === 0 ||
$this->getOldID() ) {
1032 # Non-articles (special pages etc), and old revisions
1033 return array( 'index' => 'noindex',
1034 'follow' => 'nofollow' );
1035 } elseif ( $wgOut->isPrintable() ) {
1036 # Discourage indexing of printable versions, but encourage following
1037 return array( 'index' => 'noindex',
1038 'follow' => 'follow' );
1039 } elseif ( $wgRequest->getInt( 'curid' ) ) {
1040 # For ?curid=x urls, disallow indexing
1041 return array( 'index' => 'noindex',
1042 'follow' => 'follow' );
1045 # Otherwise, construct the policy based on the various config variables.
1046 $policy = self
::formatRobotPolicy( $wgDefaultRobotPolicy );
1048 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
1049 # Honour customised robot policies for this namespace
1050 $policy = array_merge( $policy,
1051 self
::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] ) );
1053 if ( $this->mTitle
->canUseNoindex() && is_object( $this->mParserOutput
) && $this->mParserOutput
->getIndexPolicy() ) {
1054 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1055 # a final sanity check that we have really got the parser output.
1056 $policy = array_merge( $policy,
1057 array( 'index' => $this->mParserOutput
->getIndexPolicy() ) );
1060 if ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
1061 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1062 $policy = array_merge( $policy,
1063 self
::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) );
1071 * Converts a String robot policy into an associative array, to allow
1072 * merging of several policies using array_merge().
1073 * @param $policy Mixed, returns empty array on null/false/'', transparent
1074 * to already-converted arrays, converts String.
1075 * @return associative Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1077 public static function formatRobotPolicy( $policy ) {
1078 if ( is_array( $policy ) ) {
1080 } elseif ( !$policy ) {
1084 $policy = explode( ',', $policy );
1085 $policy = array_map( 'trim', $policy );
1088 foreach ( $policy as $var ) {
1089 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
1090 $arr['index'] = $var;
1091 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
1092 $arr['follow'] = $var;
1099 * If this request is a redirect view, send "redirected from" subtitle to
1100 * $wgOut. Returns true if the header was needed, false if this is not a
1101 * redirect view. Handles both local and remote redirects.
1103 public function showRedirectedFromHeader() {
1104 global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
1106 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1107 $sk = $wgUser->getSkin();
1108 if ( isset( $this->mRedirectedFrom
) ) {
1109 // This is an internally redirected page view.
1110 // We'll need a backlink to the source page for navigation.
1111 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1113 $this->mRedirectedFrom
,
1116 array( 'redirect' => 'no' ),
1117 array( 'known', 'noclasses' )
1119 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1120 $wgOut->setSubtitle( $s );
1122 // Set the fragment if one was specified in the redirect
1123 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
1124 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
1125 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1128 // Add a <link rel="canonical"> tag
1129 $wgOut->addLink( array( 'rel' => 'canonical',
1130 'href' => $this->mTitle
->getLocalURL() )
1134 } elseif ( $rdfrom ) {
1135 // This is an externally redirected view, from some other wiki.
1136 // If it was reported from a trusted site, supply a backlink.
1137 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1138 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
1139 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1140 $wgOut->setSubtitle( $s );
1148 * Show a header specific to the namespace currently being viewed, like
1149 * [[MediaWiki:Talkpagetext]]. For Article::view().
1151 public function showNamespaceHeader() {
1153 if ( $this->mTitle
->isTalkPage() ) {
1154 $msg = wfMsgNoTrans( 'talkpageheader' );
1155 if ( $msg !== '-' && !wfEmptyMsg( 'talkpageheader', $msg ) ) {
1156 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1</div>", array( 'talkpageheader' ) );
1162 * Show the footer section of an ordinary page view
1164 public function showViewFooter() {
1165 global $wgOut, $wgUseTrackbacks, $wgRequest;
1166 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1167 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& IP
::isValid( $this->mTitle
->getText() ) ) {
1168 $wgOut->addWikiMsg( 'anontalkpagetext' );
1171 # If we have been passed an &rcid= parameter, we want to give the user a
1172 # chance to mark this new article as patrolled.
1173 $this->showPatrolFooter();
1176 if ( $wgUseTrackbacks ) {
1177 $this->addTrackbacks();
1182 * If patrol is possible, output a patrol UI box. This is called from the
1183 * footer section of ordinary page views. If patrol is not possible or not
1184 * desired, does nothing.
1186 public function showPatrolFooter() {
1187 global $wgOut, $wgRequest, $wgUser;
1188 $rcid = $wgRequest->getVal( 'rcid' );
1190 if ( !$rcid ||
!$this->mTitle
->exists() ||
!$this->mTitle
->quickUserCan( 'patrol' ) ) {
1194 $sk = $wgUser->getSkin();
1197 "<div class='patrollink'>" .
1199 'markaspatrolledlink',
1202 wfMsgHtml( 'markaspatrolledtext' ),
1205 'action' => 'markpatrolled',
1208 array( 'known', 'noclasses' )
1216 * Show the error text for a missing article. For articles in the MediaWiki
1217 * namespace, show the default message text. To be called from Article::view().
1219 public function showMissingArticle() {
1220 global $wgOut, $wgRequest, $wgUser;
1222 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1223 if ( $this->mTitle
->getNamespace() == NS_USER ||
$this->mTitle
->getNamespace() == NS_USER_TALK
) {
1224 $parts = explode( '/', $this->mTitle
->getText() );
1225 $rootPart = $parts[0];
1226 $user = User
::newFromName( $rootPart, false /* allow IP users*/ );
1227 $ip = User
::isIP( $rootPart );
1228 if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
1229 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1</div>",
1230 array( 'userpage-userdoesnotexist-view', $rootPart ) );
1231 } else if ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1232 LogEventsList
::showLogExtract(
1235 $user->getUserPage()->getPrefixedText(),
1239 'showIfEmpty' => false,
1241 'blocked-notice-logextract',
1242 $user->getName() # Support GENDER in notice
1248 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1249 # Show delete and move logs
1250 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
->getPrefixedText(), '',
1252 'conds' => array( "log_action != 'revision'" ),
1253 'showIfEmpty' => false,
1254 'msgKey' => array( 'moveddeleted-notice' ) )
1257 # Show error message
1258 $oldid = $this->getOldID();
1260 $text = wfMsgNoTrans( 'missing-article',
1261 $this->mTitle
->getPrefixedText(),
1262 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1263 } elseif ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
) {
1264 // Use the default message text
1265 $text = $this->getContent();
1267 $createErrors = $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser );
1268 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
1269 $errors = array_merge( $createErrors, $editErrors );
1271 if ( !count( $errors ) )
1272 $text = wfMsgNoTrans( 'noarticletext' );
1274 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1276 $text = "<div class='noarticletext'>\n$text\n</div>";
1277 if ( !$this->hasViewableContent() ) {
1278 // If there's no backing content, send a 404 Not Found
1279 // for better machine handling of broken links.
1280 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
1282 $wgOut->addWikiText( $text );
1286 * If the revision requested for view is deleted, check permissions.
1287 * Send either an error message or a warning header to $wgOut.
1288 * Returns true if the view is allowed, false if not.
1290 public function showDeletedRevisionHeader() {
1291 global $wgOut, $wgRequest;
1292 if ( !$this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1296 // If the user is not allowed to see it...
1297 if ( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1298 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1299 'rev-deleted-text-permission' );
1301 // If the user needs to confirm that they want to see it...
1302 } else if ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1303 # Give explanation and add a link to view the revision...
1304 $oldid = intval( $this->getOldID() );
1305 $link = $this->mTitle
->getFullUrl( "oldid={$oldid}&unhide=1" );
1306 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1307 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1308 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1309 array( $msg, $link ) );
1311 // We are allowed to see...
1313 $msg = $this->mRevision
->isDeleted( Revision
::DELETED_RESTRICTED
) ?
1314 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1315 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", $msg );
1321 * Should the parser cache be used?
1323 public function useParserCache( $oldid ) {
1324 global $wgUser, $wgEnableParserCache;
1326 return $wgEnableParserCache
1327 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1330 && !$this->mTitle
->isCssOrJsPage()
1331 && !$this->mTitle
->isCssJsSubpage();
1335 * Execute the uncached parse for action=view
1337 public function doViewParse() {
1339 $oldid = $this->getOldID();
1340 $useParserCache = $this->useParserCache( $oldid );
1341 $parserOptions = clone $this->getParserOptions();
1342 # Render printable version, use printable version cache
1343 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1344 # Don't show section-edit links on old revisions... this way lies madness.
1345 $parserOptions->setEditSection( $this->isCurrent() );
1346 $useParserCache = $this->useParserCache( $oldid );
1347 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1351 * Try to fetch an expired entry from the parser cache. If it is present,
1352 * output it and return true. If it is not present, output nothing and
1353 * return false. This is used as a callback function for
1354 * PoolCounter::executeProtected().
1356 public function tryDirtyCache() {
1358 $parserCache = ParserCache
::singleton();
1359 $options = $this->getParserOptions();
1360 $options->setIsPrintable( $wgOut->isPrintable() );
1361 $output = $parserCache->getDirty( $this, $options );
1363 wfDebug( __METHOD__
. ": sending dirty output\n" );
1364 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1365 $wgOut->setSquidMaxage( 0 );
1366 $this->mParserOutput
= $output;
1367 $wgOut->addParserOutput( $output );
1368 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1371 wfDebugLog( 'dirty', "dirty missing\n" );
1372 wfDebug( __METHOD__
. ": no dirty cache\n" );
1378 * Show an error page for an error from the pool counter.
1379 * @param $status Status
1381 public function showPoolError( $status ) {
1383 $wgOut->clearHTML(); // for release() errors
1384 $wgOut->enableClientCache( false );
1385 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1386 $wgOut->addWikiText(
1387 '<div class="errorbox">' .
1388 $status->getWikiText( false, 'view-pool-error' ) .
1395 * @param $target Title object or Array of destination(s) to redirect
1396 * @param $appendSubtitle Boolean [optional]
1397 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1399 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1400 global $wgOut, $wgContLang, $wgStylePath, $wgUser;
1402 if ( !is_array( $target ) ) {
1403 $target = array( $target );
1405 $imageDir = $wgContLang->getDir();
1406 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1407 $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1408 $alt2 = $wgContLang->isRTL() ?
'←' : '→'; // should -> and <- be used instead of entities?
1410 if ( $appendSubtitle ) {
1411 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1413 $sk = $wgUser->getSkin();
1414 // the loop prepends the arrow image before the link, so the first case needs to be outside
1415 $title = array_shift( $target );
1416 if ( $forceKnown ) {
1419 htmlspecialchars( $title->getFullText() ),
1422 array( 'known', 'noclasses' )
1425 $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
1427 // automatically append redirect=no to each link, since most of them are redirect pages themselves
1428 foreach ( $target as $rt ) {
1429 if ( $forceKnown ) {
1430 $link .= '<img src="' . $imageUrl2 . '" alt="' . $alt2 . ' " />'
1433 htmlspecialchars( $rt->getFullText() ),
1436 array( 'known', 'noclasses' )
1439 $link .= '<img src="' . $imageUrl2 . '" alt="' . $alt2 . ' " />'
1440 . $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
1443 return '<img src="' . $imageUrl . '" alt="#REDIRECT " />' .
1444 '<span class="redirectText">' . $link . '</span>';
1448 public function addTrackbacks() {
1449 global $wgOut, $wgUser;
1450 $dbr = wfGetDB( DB_SLAVE
);
1451 $tbs = $dbr->select( 'trackbacks',
1452 array( 'tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name' ),
1453 array( 'tb_page' => $this->getID() )
1455 if ( !$dbr->numRows( $tbs ) ) return;
1458 while ( $o = $dbr->fetchObject( $tbs ) ) {
1460 if ( $wgUser->isAllowed( 'trackback' ) ) {
1461 $delurl = $this->mTitle
->getFullURL( "action=deletetrackback&tbid=" .
1462 $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
1463 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1466 $tbtext .= wfMsg( strlen( $o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
1473 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>$1</div>\n", array( 'trackbackbox', $tbtext ) );
1474 $this->mTitle
->invalidateCache();
1477 public function deletetrackback() {
1478 global $wgUser, $wgRequest, $wgOut;
1479 if ( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ) ) ) {
1480 $wgOut->addWikiMsg( 'sessionfailure' );
1484 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1485 if ( count( $permission_errors ) ) {
1486 $wgOut->showPermissionsErrorPage( $permission_errors );
1490 $db = wfGetDB( DB_MASTER
);
1491 $db->delete( 'trackbacks', array( 'tb_id' => $wgRequest->getInt( 'tbid' ) ) );
1493 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1494 $this->mTitle
->invalidateCache();
1497 public function render() {
1499 $wgOut->setArticleBodyOnly( true );
1504 * Handle action=purge
1506 public function purge() {
1507 global $wgUser, $wgRequest, $wgOut;
1508 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
1509 if ( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1514 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1515 $button = wfMsgExt( 'confirm_purge_button', array( 'escapenoentities' ) );
1516 $form = "<form method=\"post\" action=\"$action\">\n" .
1517 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1519 $top = wfMsgExt( 'confirm-purge-top', array( 'parse' ) );
1520 $bottom = wfMsgExt( 'confirm-purge-bottom', array( 'parse' ) );
1521 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1522 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1523 $wgOut->addHTML( $top . $form . $bottom );
1528 * Perform the actions of a page purging
1530 public function doPurge() {
1532 // Invalidate the cache
1533 $this->mTitle
->invalidateCache();
1535 if ( $wgUseSquid ) {
1536 // Commit the transaction before the purge is sent
1537 $dbw = wfGetDB( DB_MASTER
);
1541 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1542 $update->doUpdate();
1544 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1545 global $wgMessageCache;
1546 if ( $this->getID() == 0 ) {
1549 $text = $this->getRawText();
1551 $wgMessageCache->replace( $this->mTitle
->getDBkey(), $text );
1556 * Insert a new empty page record for this article.
1557 * This *must* be followed up by creating a revision
1558 * and running $this->updateToLatest( $rev_id );
1559 * or else the record will be left in a funky state.
1560 * Best if all done inside a transaction.
1562 * @param $dbw Database
1563 * @return int The newly created page_id key, or false if the title already existed
1566 public function insertOn( $dbw ) {
1567 wfProfileIn( __METHOD__
);
1569 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1570 $dbw->insert( 'page', array(
1571 'page_id' => $page_id,
1572 'page_namespace' => $this->mTitle
->getNamespace(),
1573 'page_title' => $this->mTitle
->getDBkey(),
1574 'page_counter' => 0,
1575 'page_restrictions' => '',
1576 'page_is_redirect' => 0, # Will set this shortly...
1578 'page_random' => wfRandom(),
1579 'page_touched' => $dbw->timestamp(),
1580 'page_latest' => 0, # Fill this in shortly...
1581 'page_len' => 0, # Fill this in shortly...
1582 ), __METHOD__
, 'IGNORE' );
1584 $affected = $dbw->affectedRows();
1586 $newid = $dbw->insertId();
1587 $this->mTitle
->resetArticleId( $newid );
1589 wfProfileOut( __METHOD__
);
1590 return $affected ?
$newid : false;
1594 * Update the page record to point to a newly saved revision.
1596 * @param $dbw Database object
1597 * @param $revision Revision: For ID number, and text used to set
1598 length and redirect status fields
1599 * @param $lastRevision Integer: if given, will not overwrite the page field
1600 * when different from the currently set value.
1601 * Giving 0 indicates the new page flag should be set
1603 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1604 * removing rows in redirect table.
1605 * @return bool true on success, false on failure
1608 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1609 wfProfileIn( __METHOD__
);
1611 $text = $revision->getText();
1612 $rt = Title
::newFromRedirect( $text );
1614 $conditions = array( 'page_id' => $this->getId() );
1615 if ( !is_null( $lastRevision ) ) {
1616 # An extra check against threads stepping on each other
1617 $conditions['page_latest'] = $lastRevision;
1620 $dbw->update( 'page',
1622 'page_latest' => $revision->getId(),
1623 'page_touched' => $dbw->timestamp(),
1624 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1625 'page_is_redirect' => $rt !== null ?
1 : 0,
1626 'page_len' => strlen( $text ),
1631 $result = $dbw->affectedRows() != 0;
1633 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1636 wfProfileOut( __METHOD__
);
1641 * Add row to the redirect table if this is a redirect, remove otherwise.
1643 * @param $dbw Database
1644 * @param $redirectTitle a title object pointing to the redirect target,
1645 * or NULL if this is not a redirect
1646 * @param $lastRevIsRedirect If given, will optimize adding and
1647 * removing rows in redirect table.
1648 * @return bool true on success, false on failure
1651 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1652 // Always update redirects (target link might have changed)
1653 // Update/Insert if we don't know if the last revision was a redirect or not
1654 // Delete if changing from redirect to non-redirect
1655 $isRedirect = !is_null( $redirectTitle );
1656 if ( $isRedirect ||
is_null( $lastRevIsRedirect ) ||
$lastRevIsRedirect !== $isRedirect ) {
1657 wfProfileIn( __METHOD__
);
1658 if ( $isRedirect ) {
1659 // This title is a redirect, Add/Update row in the redirect table
1660 $set = array( /* SET */
1661 'rd_namespace' => $redirectTitle->getNamespace(),
1662 'rd_title' => $redirectTitle->getDBkey(),
1663 'rd_from' => $this->getId(),
1665 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1667 // This is not a redirect, remove row from redirect table
1668 $where = array( 'rd_from' => $this->getId() );
1669 $dbw->delete( 'redirect', $where, __METHOD__
);
1671 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1672 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1674 wfProfileOut( __METHOD__
);
1675 return ( $dbw->affectedRows() != 0 );
1681 * If the given revision is newer than the currently set page_latest,
1682 * update the page record. Otherwise, do nothing.
1684 * @param $dbw Database object
1685 * @param $revision Revision object
1687 public function updateIfNewerOn( &$dbw, $revision ) {
1688 wfProfileIn( __METHOD__
);
1689 $row = $dbw->selectRow(
1690 array( 'revision', 'page' ),
1691 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1693 'page_id' => $this->getId(),
1694 'page_latest=rev_id' ),
1697 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1698 wfProfileOut( __METHOD__
);
1701 $prev = $row->rev_id
;
1702 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1704 # No or missing previous revision; mark the page as new
1706 $lastRevIsRedirect = null;
1708 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1709 wfProfileOut( __METHOD__
);
1714 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1715 * @return string Complete article text, or null if error
1717 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1718 wfProfileIn( __METHOD__
);
1719 if ( strval( $section ) == '' ) {
1720 // Whole-page edit; let the whole text through
1722 if ( is_null( $edittime ) ) {
1723 $rev = Revision
::newFromTitle( $this->mTitle
);
1725 $dbw = wfGetDB( DB_MASTER
);
1726 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1729 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1730 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1733 $oldtext = $rev->getText();
1735 if ( $section == 'new' ) {
1736 # Inserting a new section
1737 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1738 $text = strlen( trim( $oldtext ) ) > 0
1739 ?
"{$oldtext}\n\n{$subject}{$text}"
1740 : "{$subject}{$text}";
1742 # Replacing an existing section; roll out the big guns
1744 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1747 wfProfileOut( __METHOD__
);
1752 * This function is not deprecated until somebody fixes the core not to use
1753 * it. Nevertheless, use Article::doEdit() instead.
1755 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC = false, $comment = false, $bot = false ) {
1756 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1757 ( $isminor ? EDIT_MINOR
: 0 ) |
1758 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1759 ( $bot ? EDIT_FORCE_BOT
: 0 );
1761 # If this is a comment, add the summary as headline
1762 if ( $comment && $summary != "" ) {
1763 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" . $text;
1766 $this->doEdit( $text, $summary, $flags );
1768 $dbw = wfGetDB( DB_MASTER
);
1770 if ( !$this->mTitle
->userIsWatching() ) {
1776 if ( $this->mTitle
->userIsWatching() ) {
1782 $this->doRedirect( $this->isRedirect( $text ) );
1786 * @deprecated use Article::doEdit()
1788 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1789 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1790 ( $minor ? EDIT_MINOR
: 0 ) |
1791 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1793 $status = $this->doEdit( $text, $summary, $flags );
1794 if ( !$status->isOK() ) {
1798 $dbw = wfGetDB( DB_MASTER
);
1800 if ( !$this->mTitle
->userIsWatching() ) {
1806 if ( $this->mTitle
->userIsWatching() ) {
1813 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1814 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1816 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1823 * Change an existing article or create a new article. Updates RC and all necessary caches,
1824 * optionally via the deferred update array.
1826 * $wgUser must be set before calling this function.
1828 * @param $text String: new text
1829 * @param $summary String: edit summary
1830 * @param $flags Integer bitfield:
1832 * Article is known or assumed to be non-existent, create a new one
1834 * Article is known or assumed to be pre-existing, update it
1836 * Mark this edit minor, if the user is allowed to do so
1838 * Do not log the change in recentchanges
1840 * Mark the edit a "bot" edit regardless of user rights
1841 * EDIT_DEFER_UPDATES
1842 * Defer some of the updates until the end of index.php
1844 * Fill in blank summaries with generated text where possible
1846 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1847 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1848 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1849 * edit-already-exists error will be returned. These two conditions are also possible with
1850 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1852 * @param $baseRevId the revision ID this edit was based off, if any
1853 * @param $user Optional user object, $wgUser will be used if not passed
1855 * @return Status object. Possible errors:
1856 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1857 * edit-gone-missing: In update mode, but the article didn't exist
1858 * edit-conflict: In update mode, the article changed unexpectedly
1859 * edit-no-change: Warning that the text was the same as before
1860 * edit-already-exists: In creation mode, but the article already exists
1862 * Extensions may define additional errors.
1864 * $return->value will contain an associative array with members as follows:
1865 * new: Boolean indicating if the function attempted to create a new article
1866 * revision: The revision object for the inserted revision, or null
1868 * Compatibility note: this function previously returned a boolean value indicating success/failure
1870 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1871 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1873 # Low-level sanity check
1874 if ( $this->mTitle
->getText() == '' ) {
1875 throw new MWException( 'Something is trying to edit an article with an empty title' );
1878 wfProfileIn( __METHOD__
);
1880 $user = is_null( $user ) ?
$wgUser : $user;
1881 $status = Status
::newGood( array() );
1883 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1884 $this->loadPageData();
1886 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1887 $aid = $this->mTitle
->getArticleID();
1889 $flags |
= EDIT_UPDATE
;
1895 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1896 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1898 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1899 wfProfileOut( __METHOD__
);
1900 if ( $status->isOK() ) {
1901 $status->fatal( 'edit-hook-aborted' );
1906 # Silently ignore EDIT_MINOR if not allowed
1907 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1908 $bot = $flags & EDIT_FORCE_BOT
;
1910 $oldtext = $this->getRawText(); // current revision
1911 $oldsize = strlen( $oldtext );
1913 # Provide autosummaries if one is not provided and autosummaries are enabled.
1914 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1915 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1918 $editInfo = $this->prepareTextForEdit( $text );
1919 $text = $editInfo->pst
;
1920 $newsize = strlen( $text );
1922 $dbw = wfGetDB( DB_MASTER
);
1923 $now = wfTimestampNow();
1924 $this->mTimestamp
= $now;
1926 if ( $flags & EDIT_UPDATE
) {
1927 # Update article, but only if changed.
1928 $status->value
['new'] = false;
1929 # Make sure the revision is either completely inserted or not inserted at all
1930 if ( !$wgDBtransactions ) {
1931 $userAbort = ignore_user_abort( true );
1936 $changed = ( strcmp( $text, $oldtext ) != 0 );
1939 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1940 - (int)$this->isCountable( $oldtext );
1941 $this->mTotalAdjustment
= 0;
1943 if ( !$this->mLatest
) {
1944 # Article gone missing
1945 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1946 $status->fatal( 'edit-gone-missing' );
1947 wfProfileOut( __METHOD__
);
1951 $revision = new Revision( array(
1952 'page' => $this->getId(),
1953 'comment' => $summary,
1954 'minor_edit' => $isminor,
1956 'parent_id' => $this->mLatest
,
1957 'user' => $user->getId(),
1958 'user_text' => $user->getName(),
1962 $revisionId = $revision->insertOn( $dbw );
1966 # Note that we use $this->mLatest instead of fetching a value from the master DB
1967 # during the course of this function. This makes sure that EditPage can detect
1968 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1969 # before this function is called. A previous function used a separate query, this
1970 # creates a window where concurrent edits can cause an ignored edit conflict.
1971 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
1974 /* Belated edit conflict! Run away!! */
1975 $status->fatal( 'edit-conflict' );
1976 # Delete the invalid revision if the DB is not transactional
1977 if ( !$wgDBtransactions ) {
1978 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1983 global $wgUseRCPatrol;
1984 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1985 # Update recentchanges
1986 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1987 # Mark as patrolled if the user can do so
1988 $patrolled = $wgUseRCPatrol && $this->mTitle
->userCan( 'autopatrol' );
1989 # Add RC row to the DB
1990 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1991 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1992 $revisionId, $patrolled
1994 # Log auto-patrolled edits
1996 PatrolLog
::record( $rc, true );
1999 $user->incEditCount();
2003 $status->warning( 'edit-no-change' );
2005 // Keep the same revision ID, but do some updates on it
2006 $revisionId = $this->getRevIdFetched();
2007 // Update page_touched, this is usually implicit in the page update
2008 // Other cache updates are done in onArticleEdit()
2009 $this->mTitle
->invalidateCache();
2012 if ( !$wgDBtransactions ) {
2013 ignore_user_abort( $userAbort );
2015 // Now that ignore_user_abort is restored, we can respond to fatal errors
2016 if ( !$status->isOK() ) {
2017 wfProfileOut( __METHOD__
);
2021 # Invalidate cache of this article and all pages using this article
2022 # as a template. Partly deferred.
2023 Article
::onArticleEdit( $this->mTitle
);
2024 # Update links tables, site stats, etc.
2025 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
2027 # Create new article
2028 $status->value
['new'] = true;
2030 # Set statistics members
2031 # We work out if it's countable after PST to avoid counter drift
2032 # when articles are created with {{subst:}}
2033 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
2034 $this->mTotalAdjustment
= 1;
2038 # Add the page record; stake our claim on this title!
2039 # This will return false if the article already exists
2040 $newid = $this->insertOn( $dbw );
2042 if ( $newid === false ) {
2044 $status->fatal( 'edit-already-exists' );
2045 wfProfileOut( __METHOD__
);
2049 # Save the revision text...
2050 $revision = new Revision( array(
2052 'comment' => $summary,
2053 'minor_edit' => $isminor,
2055 'user' => $user->getId(),
2056 'user_text' => $user->getName(),
2058 $revisionId = $revision->insertOn( $dbw );
2060 $this->mTitle
->resetArticleID( $newid );
2062 # Update the page record with revision data
2063 $this->updateRevisionOn( $dbw, $revision, 0 );
2065 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2066 # Update recentchanges
2067 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
2068 global $wgUseRCPatrol, $wgUseNPPatrol;
2069 # Mark as patrolled if the user can do so
2070 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && $this->mTitle
->userCan( 'autopatrol' );
2071 # Add RC row to the DB
2072 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
2073 '', strlen( $text ), $revisionId, $patrolled );
2074 # Log auto-patrolled edits
2076 PatrolLog
::record( $rc, true );
2079 $user->incEditCount();
2082 # Update links, etc.
2083 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
2086 Article
::onArticleCreate( $this->mTitle
);
2088 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2089 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
2092 # Do updates right now unless deferral was requested
2093 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
2097 // Return the new revision (or null) to the caller
2098 $status->value
['revision'] = $revision;
2100 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2101 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
2103 wfProfileOut( __METHOD__
);
2108 * @deprecated wrapper for doRedirect
2110 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
2111 wfDeprecated( __METHOD__
);
2112 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
2116 * Output a redirect back to the article.
2117 * This is typically used after an edit.
2119 * @param $noRedir Boolean: add redirect=no
2120 * @param $sectionAnchor String: section to redirect to, including "#"
2121 * @param $extraQuery String: extra query params
2123 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2126 $query = 'redirect=no';
2128 $query .= "&$query";
2130 $query = $extraQuery;
2132 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
2136 * Mark this particular edit/page as patrolled
2138 public function markpatrolled() {
2139 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
2140 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2142 # If we haven't been given an rc_id value, we can't do anything
2143 $rcid = (int) $wgRequest->getVal( 'rcid' );
2144 $rc = RecentChange
::newFromId( $rcid );
2145 if ( is_null( $rc ) ) {
2146 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2150 # It would be nice to see where the user had actually come from, but for now just guess
2151 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ?
'Newpages' : 'Recentchanges';
2152 $return = SpecialPage
::getTitleFor( $returnto );
2154 $dbw = wfGetDB( DB_MASTER
);
2155 $errors = $rc->doMarkPatrolled();
2157 if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
2158 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2162 if ( in_array( array( 'hookaborted' ), $errors ) ) {
2163 // The hook itself has handled any output
2167 if ( in_array( array( 'markedaspatrollederror-noautopatrol' ), $errors ) ) {
2168 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2169 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2170 $wgOut->returnToMain( false, $return );
2174 if ( !empty( $errors ) ) {
2175 $wgOut->showPermissionsErrorPage( $errors );
2180 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2181 $wgOut->addWikiMsg( 'markedaspatrolledtext', $rc->getTitle()->getPrefixedText() );
2182 $wgOut->returnToMain( false, $return );
2186 * User-interface handler for the "watch" action
2188 public function watch() {
2189 global $wgUser, $wgOut;
2190 if ( $wgUser->isAnon() ) {
2191 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2194 if ( wfReadOnly() ) {
2195 $wgOut->readOnlyPage();
2198 if ( $this->doWatch() ) {
2199 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
2200 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2201 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle
->getPrefixedText() );
2203 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
2207 * Add this page to $wgUser's watchlist
2208 * @return bool true on successful watch operation
2210 public function doWatch() {
2212 if ( $wgUser->isAnon() ) {
2215 if ( wfRunHooks( 'WatchArticle', array( &$wgUser, &$this ) ) ) {
2216 $wgUser->addWatch( $this->mTitle
);
2217 return wfRunHooks( 'WatchArticleComplete', array( &$wgUser, &$this ) );
2223 * User interface handler for the "unwatch" action.
2225 public function unwatch() {
2226 global $wgUser, $wgOut;
2227 if ( $wgUser->isAnon() ) {
2228 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2231 if ( wfReadOnly() ) {
2232 $wgOut->readOnlyPage();
2235 if ( $this->doUnwatch() ) {
2236 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
2237 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2238 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle
->getPrefixedText() );
2240 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
2244 * Stop watching a page
2245 * @return bool true on successful unwatch
2247 public function doUnwatch() {
2249 if ( $wgUser->isAnon() ) {
2252 if ( wfRunHooks( 'UnwatchArticle', array( &$wgUser, &$this ) ) ) {
2253 $wgUser->removeWatch( $this->mTitle
);
2254 return wfRunHooks( 'UnwatchArticleComplete', array( &$wgUser, &$this ) );
2260 * action=protect handler
2262 public function protect() {
2263 $form = new ProtectionForm( $this );
2268 * action=unprotect handler (alias)
2270 public function unprotect() {
2275 * Update the article's restriction field, and leave a log entry.
2277 * @param $limit Array: set of restriction keys
2278 * @param $reason String
2279 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2280 * @param $expiry Array: per restriction type expiration
2281 * @return bool true on success
2283 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2284 global $wgUser, $wgContLang;
2286 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2288 $id = $this->mTitle
->getArticleID();
2290 wfDebug( "updateRestrictions failed: $id <= 0\n" );
2294 if ( wfReadOnly() ) {
2295 wfDebug( "updateRestrictions failed: read-only\n" );
2299 if ( !$this->mTitle
->userCan( 'protect' ) ) {
2300 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2308 // Take this opportunity to purge out expired restrictions
2309 Title
::purgeExpiredRestrictions();
2311 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2312 # we expect a single selection, but the schema allows otherwise.
2314 $updated = Article
::flattenRestrictions( $limit );
2316 foreach ( $restrictionTypes as $action ) {
2317 if ( isset( $expiry[$action] ) ) {
2318 # Get current restrictions on $action
2319 $aLimits = $this->mTitle
->getRestrictions( $action );
2320 $current[$action] = implode( '', $aLimits );
2321 # Are any actual restrictions being dealt with here?
2322 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
2323 # If something changed, we need to log it. Checking $aRChanged
2324 # assures that "unprotecting" a page that is not protected does
2325 # not log just because the expiry was "changed".
2326 if ( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
2332 $current = Article
::flattenRestrictions( $current );
2334 $changed = ( $changed ||
$current != $updated );
2335 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
2336 $protect = ( $updated != '' );
2338 # If nothing's changed, do nothing
2340 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2342 $dbw = wfGetDB( DB_MASTER
);
2344 # Prepare a null revision to be added to the history
2345 $modified = $current != '' && $protect;
2347 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
2349 $comment_type = 'unprotectedarticle';
2351 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
2353 # Only restrictions with the 'protect' right can cascade...
2354 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2355 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2356 # The schema allows multiple restrictions
2357 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) )
2359 $cascade_description = '';
2361 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2365 $comment .= ": $reason";
2367 $editComment = $comment;
2368 $encodedExpiry = array();
2369 $protect_description = '';
2370 foreach ( $limit as $action => $restrictions ) {
2371 if ( !isset( $expiry[$action] ) )
2372 $expiry[$action] = 'infinite';
2374 $encodedExpiry[$action] = Block
::encodeExpiry( $expiry[$action], $dbw );
2375 if ( $restrictions != '' ) {
2376 $protect_description .= "[$action=$restrictions] (";
2377 if ( $encodedExpiry[$action] != 'infinity' ) {
2378 $protect_description .= wfMsgForContent( 'protect-expiring',
2379 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2380 $wgContLang->date( $expiry[$action], false, false ) ,
2381 $wgContLang->time( $expiry[$action], false, false ) );
2383 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2385 $protect_description .= ') ';
2388 $protect_description = trim( $protect_description );
2390 if ( $protect_description && $protect )
2391 $editComment .= " ($protect_description)";
2393 $editComment .= "$cascade_description";
2394 # Update restrictions table
2395 foreach ( $limit as $action => $restrictions ) {
2396 if ( $restrictions != '' ) {
2397 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2398 array( 'pr_page' => $id,
2399 'pr_type' => $action,
2400 'pr_level' => $restrictions,
2401 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2402 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__
);
2404 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2405 'pr_type' => $action ), __METHOD__
);
2409 # Insert a null revision
2410 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2411 $nullRevId = $nullRevision->insertOn( $dbw );
2413 $latest = $this->getLatest();
2414 # Update page record
2415 $dbw->update( 'page',
2417 'page_touched' => $dbw->timestamp(),
2418 'page_restrictions' => '',
2419 'page_latest' => $nullRevId
2420 ), array( /* WHERE */
2422 ), 'Article::protect'
2425 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2426 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2428 # Update the protection log
2429 $log = new LogPage( 'protect' );
2431 $params = array( $protect_description, $cascade ?
'cascade' : '' );
2432 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
2434 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
2438 } # End "changed" check
2444 * Take an array of page restrictions and flatten it to a string
2445 * suitable for insertion into the page_restrictions field.
2446 * @param $limit Array
2449 protected static function flattenRestrictions( $limit ) {
2450 if ( !is_array( $limit ) ) {
2451 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2455 foreach ( $limit as $action => $restrictions ) {
2456 if ( $restrictions != '' ) {
2457 $bits[] = "$action=$restrictions";
2460 return implode( ':', $bits );
2464 * Auto-generates a deletion reason
2465 * @param &$hasHistory Boolean: whether the page has a history
2467 public function generateReason( &$hasHistory ) {
2469 $dbw = wfGetDB( DB_MASTER
);
2470 // Get the last revision
2471 $rev = Revision
::newFromTitle( $this->mTitle
);
2472 if ( is_null( $rev ) )
2475 // Get the article's contents
2476 $contents = $rev->getText();
2478 // If the page is blank, use the text from the previous revision,
2479 // which can only be blank if there's a move/import/protect dummy revision involved
2480 if ( $contents == '' ) {
2481 $prev = $rev->getPrevious();
2483 $contents = $prev->getText();
2488 // Find out if there was only one contributor
2489 // Only scan the last 20 revisions
2490 $res = $dbw->select( 'revision', 'rev_user_text',
2491 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2493 array( 'LIMIT' => 20 )
2495 if ( $res === false )
2496 // This page has no revisions, which is very weird
2499 $hasHistory = ( $res->numRows() > 1 );
2500 $row = $dbw->fetchObject( $res );
2501 $onlyAuthor = $row->rev_user_text
;
2502 // Try to find a second contributor
2503 foreach ( $res as $row ) {
2504 if ( $row->rev_user_text
!= $onlyAuthor ) {
2505 $onlyAuthor = false;
2509 $dbw->freeResult( $res );
2511 // Generate the summary with a '$1' placeholder
2513 // The current revision is blank and the one before is also
2514 // blank. It's just not our lucky day
2515 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2518 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2520 $reason = wfMsgForContent( 'excontent', '$1' );
2523 if ( $reason == '-' ) {
2524 // Allow these UI messages to be blanked out cleanly
2528 // Replace newlines with spaces to prevent uglyness
2529 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2530 // Calculate the maximum amount of chars to get
2531 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2532 $maxLength = 255 - ( strlen( $reason ) - 2 ) - 3;
2533 $contents = $wgContLang->truncate( $contents, $maxLength );
2534 // Remove possible unfinished links
2535 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2536 // Now replace the '$1' placeholder
2537 $reason = str_replace( '$1', $contents, $reason );
2543 * UI entry point for page deletion
2545 public function delete() {
2546 global $wgUser, $wgOut, $wgRequest;
2548 $confirm = $wgRequest->wasPosted() &&
2549 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2551 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2552 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
2554 $reason = $this->DeleteReasonList
;
2556 if ( $reason != 'other' && $this->DeleteReason
!= '' ) {
2557 // Entry from drop down menu + additional comment
2558 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason
;
2559 } elseif ( $reason == 'other' ) {
2560 $reason = $this->DeleteReason
;
2562 # Flag to hide all contents of the archived revisions
2563 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2565 # This code desperately needs to be totally rewritten
2567 # Read-only check...
2568 if ( wfReadOnly() ) {
2569 $wgOut->readOnlyPage();
2574 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
2576 if ( count( $permission_errors ) > 0 ) {
2577 $wgOut->showPermissionsErrorPage( $permission_errors );
2581 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle
->getPrefixedText() ) );
2583 # Better double-check that it hasn't been deleted yet!
2584 $dbw = wfGetDB( DB_MASTER
);
2585 $conds = $this->mTitle
->pageCond();
2586 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
2587 if ( $latest === false ) {
2588 $wgOut->showFatalError(
2591 array( 'class' => 'error mw-error-cannotdelete' ),
2592 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
2595 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2596 LogEventsList
::showLogExtract(
2599 $this->mTitle
->getPrefixedText()
2604 # Hack for big sites
2605 $bigHistory = $this->isBigDeletion();
2606 if ( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
2607 global $wgLang, $wgDeleteRevisionsLimit;
2608 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2609 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2614 $this->doDelete( $reason, $suppress );
2615 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgUser->isLoggedIn() ) {
2617 } elseif ( $this->mTitle
->userIsWatching() ) {
2623 // Generate deletion reason
2624 $hasHistory = false;
2625 if ( !$reason ) $reason = $this->generateReason( $hasHistory );
2627 // If the page has a history, insert a warning
2628 if ( $hasHistory && !$confirm ) {
2630 $skin = $wgUser->getSkin();
2631 $revisions = $this->estimateRevisionCount();
2632 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2633 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2634 wfMsgHtml( 'word-separator' ) . $skin->historyLink() .
2637 if ( $bigHistory ) {
2638 global $wgDeleteRevisionsLimit;
2639 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2640 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2644 return $this->confirmDelete( $reason );
2648 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2650 public function isBigDeletion() {
2651 global $wgDeleteRevisionsLimit;
2652 if ( $wgDeleteRevisionsLimit ) {
2653 $revCount = $this->estimateRevisionCount();
2654 return $revCount > $wgDeleteRevisionsLimit;
2660 * @return int approximate revision count
2662 public function estimateRevisionCount() {
2663 $dbr = wfGetDB( DB_SLAVE
);
2664 // For an exact count...
2665 // return $dbr->selectField( 'revision', 'COUNT(*)',
2666 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2667 return $dbr->estimateRowCount( 'revision', '*',
2668 array( 'rev_page' => $this->getId() ), __METHOD__
);
2672 * Get the last N authors
2673 * @param $num Integer: number of revisions to get
2674 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2675 * @return array Array of authors, duplicates not removed
2677 public function getLastNAuthors( $num, $revLatest = 0 ) {
2678 wfProfileIn( __METHOD__
);
2679 // First try the slave
2680 // If that doesn't have the latest revision, try the master
2682 $db = wfGetDB( DB_SLAVE
);
2684 $res = $db->select( array( 'page', 'revision' ),
2685 array( 'rev_id', 'rev_user_text' ),
2687 'page_namespace' => $this->mTitle
->getNamespace(),
2688 'page_title' => $this->mTitle
->getDBkey(),
2689 'rev_page = page_id'
2690 ), __METHOD__
, $this->getSelectOptions( array(
2691 'ORDER BY' => 'rev_timestamp DESC',
2696 wfProfileOut( __METHOD__
);
2699 $row = $db->fetchObject( $res );
2700 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2701 $db = wfGetDB( DB_MASTER
);
2706 } while ( $continue );
2708 $authors = array( $row->rev_user_text
);
2709 while ( $row = $db->fetchObject( $res ) ) {
2710 $authors[] = $row->rev_user_text
;
2712 wfProfileOut( __METHOD__
);
2717 * Output deletion confirmation dialog
2718 * @param $reason String: prefilled reason
2720 public function confirmDelete( $reason ) {
2721 global $wgOut, $wgUser;
2723 wfDebug( "Article::confirmDelete\n" );
2725 $deleteBackLink = $wgUser->getSkin()->link(
2730 array( 'known', 'noclasses' )
2732 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2733 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2734 $wgOut->addWikiMsg( 'confirmdeletetext' );
2736 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
2738 if ( $wgUser->isAllowed( 'suppressrevision' ) ) {
2739 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2741 <td class='mw-input'><strong>" .
2742 Xml
::checkLabel( wfMsg( 'revdelete-suppress' ),
2743 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2749 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching();
2751 $form = Xml
::openElement( 'form', array( 'method' => 'post',
2752 'action' => $this->mTitle
->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2753 Xml
::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2754 Xml
::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2755 Xml
::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2756 "<tr id=\"wpDeleteReasonListRow\">
2757 <td class='mw-label'>" .
2758 Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2760 <td class='mw-input'>" .
2761 Xml
::listDropDown( 'wpDeleteReasonList',
2762 wfMsgForContent( 'deletereason-dropdown' ),
2763 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2766 <tr id=\"wpDeleteReasonRow\">
2767 <td class='mw-label'>" .
2768 Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2770 <td class='mw-input'>" .
2771 Html
::input( 'wpReason', $reason, 'text', array(
2773 'maxlength' => '255',
2780 # Dissalow watching is user is not logged in
2781 if ( $wgUser->isLoggedIn() ) {
2785 <td class='mw-input'>" .
2786 Xml
::checkLabel( wfMsg( 'watchthis' ),
2787 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2795 <td class='mw-submit'>" .
2796 Xml
::submitButton( wfMsg( 'deletepage' ),
2797 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2800 Xml
::closeElement( 'table' ) .
2801 Xml
::closeElement( 'fieldset' ) .
2802 Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) .
2803 Xml
::closeElement( 'form' );
2805 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2806 $skin = $wgUser->getSkin();
2807 $title = Title
::makeTitle( NS_MEDIAWIKI
, 'Deletereason-dropdown' );
2808 $link = $skin->link(
2810 wfMsgHtml( 'delete-edit-reasonlist' ),
2812 array( 'action' => 'edit' )
2814 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2817 $wgOut->addHTML( $form );
2818 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2819 LogEventsList
::showLogExtract(
2822 $this->mTitle
->getPrefixedText()
2827 * Perform a deletion and output success or failure messages
2829 public function doDelete( $reason, $suppress = false ) {
2830 global $wgOut, $wgUser;
2831 $id = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2834 if ( wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
2835 if ( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2836 $deleted = $this->mTitle
->getPrefixedText();
2838 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2839 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2841 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2843 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2844 $wgOut->returnToMain( false );
2845 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
2848 if ( $error == '' ) {
2849 $wgOut->showFatalError(
2852 array( 'class' => 'error mw-error-cannotdelete' ),
2853 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle
->getPrefixedText() )
2856 $wgOut->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'delete' ) ) );
2857 LogEventsList
::showLogExtract(
2860 $this->mTitle
->getPrefixedText()
2863 $wgOut->showFatalError( $error );
2869 * Back-end article deletion
2870 * Deletes the article with database consistency, writes logs, purges caches
2873 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true ) {
2874 global $wgUseSquid, $wgDeferredUpdateList;
2875 global $wgUseTrackbacks;
2877 wfDebug( __METHOD__
. "\n" );
2879 $dbw = wfGetDB( DB_MASTER
);
2880 $ns = $this->mTitle
->getNamespace();
2881 $t = $this->mTitle
->getDBkey();
2882 $id = $id ?
$id : $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
2884 if ( $t == '' ||
$id == 0 ) {
2888 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable( $this->getRawText() ), -1 );
2889 array_push( $wgDeferredUpdateList, $u );
2891 // Bitfields to further suppress the content
2894 // This should be 15...
2895 $bitfield |
= Revision
::DELETED_TEXT
;
2896 $bitfield |
= Revision
::DELETED_COMMENT
;
2897 $bitfield |
= Revision
::DELETED_USER
;
2898 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2900 $bitfield = 'rev_deleted';
2904 // For now, shunt the revision data into the archive table.
2905 // Text is *not* removed from the text table; bulk storage
2906 // is left intact to avoid breaking block-compression or
2907 // immutable storage schemes.
2909 // For backwards compatibility, note that some older archive
2910 // table entries will have ar_text and ar_flags fields still.
2912 // In the future, we may keep revisions and mark them with
2913 // the rev_deleted field, which is reserved for this purpose.
2914 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2916 'ar_namespace' => 'page_namespace',
2917 'ar_title' => 'page_title',
2918 'ar_comment' => 'rev_comment',
2919 'ar_user' => 'rev_user',
2920 'ar_user_text' => 'rev_user_text',
2921 'ar_timestamp' => 'rev_timestamp',
2922 'ar_minor_edit' => 'rev_minor_edit',
2923 'ar_rev_id' => 'rev_id',
2924 'ar_text_id' => 'rev_text_id',
2925 'ar_text' => '\'\'', // Be explicit to appease
2926 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2927 'ar_len' => 'rev_len',
2928 'ar_page_id' => 'page_id',
2929 'ar_deleted' => $bitfield
2932 'page_id = rev_page'
2936 # Delete restrictions for it
2937 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2939 # Now that it's safely backed up, delete it
2940 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2941 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2947 # Fix category table counts
2949 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2950 foreach ( $res as $row ) {
2951 $cats [] = $row->cl_to
;
2953 $this->updateCategoryCounts( array(), $cats );
2955 # If using cascading deletes, we can skip some explicit deletes
2956 if ( !$dbw->cascadingDeletes() ) {
2957 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2959 if ( $wgUseTrackbacks )
2960 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2962 # Delete outgoing links
2963 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2964 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2965 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2966 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2967 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2968 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2969 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2972 # If using cleanup triggers, we can skip some manual deletes
2973 if ( !$dbw->cleanupTriggers() ) {
2974 # Clean up recentchanges entries...
2975 $dbw->delete( 'recentchanges',
2976 array( 'rc_type != ' . RC_LOG
,
2977 'rc_namespace' => $this->mTitle
->getNamespace(),
2978 'rc_title' => $this->mTitle
->getDBkey() ),
2980 $dbw->delete( 'recentchanges',
2981 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2986 Article
::onArticleDelete( $this->mTitle
);
2988 # Clear the cached article id so the interface doesn't act like we exist
2989 $this->mTitle
->resetArticleID( 0 );
2991 # Log the deletion, if the page was suppressed, log it at Oversight instead
2992 $logtype = $suppress ?
'suppress' : 'delete';
2993 $log = new LogPage( $logtype );
2995 # Make sure logging got through
2996 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
3006 * Roll back the most recent consecutive set of edits to a page
3007 * from the same user; fails if there are no eligible edits to
3008 * roll back to, e.g. user is the sole contributor. This function
3009 * performs permissions checks on $wgUser, then calls commitRollback()
3010 * to do the dirty work
3012 * @param $fromP String: Name of the user whose edits to rollback.
3013 * @param $summary String: Custom summary. Set to default summary if empty.
3014 * @param $token String: Rollback token.
3015 * @param $bot Boolean: If true, mark all reverted edits as bot.
3017 * @param $resultDetails Array: contains result-specific array of additional values
3018 * 'alreadyrolled' : 'current' (rev)
3019 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3021 * @return array of errors, each error formatted as
3022 * array(messagekey, param1, param2, ...).
3023 * On success, the array is empty. This array can also be passed to
3024 * OutputPage::showPermissionsErrorPage().
3026 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3028 $resultDetails = null;
3031 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
3032 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
3033 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3035 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
3036 $errors[] = array( 'sessionfailure' );
3038 if ( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
3039 $errors[] = array( 'actionthrottledtext' );
3041 # If there were errors, bail out now
3042 if ( !empty( $errors ) )
3045 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3049 * Backend implementation of doRollback(), please refer there for parameter
3050 * and return value documentation
3052 * NOTE: This function does NOT check ANY permissions, it just commits the
3053 * rollback to the DB Therefore, you should only call this function direct-
3054 * ly if you want to use custom permissions checks. If you don't, use
3055 * doRollback() instead.
3057 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3058 global $wgUseRCPatrol, $wgUser, $wgLang;
3059 $dbw = wfGetDB( DB_MASTER
);
3061 if ( wfReadOnly() ) {
3062 return array( array( 'readonlytext' ) );
3065 # Get the last editor
3066 $current = Revision
::newFromTitle( $this->mTitle
);
3067 if ( is_null( $current ) ) {
3068 # Something wrong... no page?
3069 return array( array( 'notanarticle' ) );
3072 $from = str_replace( '_', ' ', $fromP );
3073 # User name given should match up with the top revision.
3074 # If the user was deleted then $from should be empty.
3075 if ( $from != $current->getUserText() ) {
3076 $resultDetails = array( 'current' => $current );
3077 return array( array( 'alreadyrolled',
3078 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3079 htmlspecialchars( $fromP ),
3080 htmlspecialchars( $current->getUserText() )
3084 # Get the last edit not by this guy...
3085 # Note: these may not be public values
3086 $user = intval( $current->getRawUser() );
3087 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3088 $s = $dbw->selectRow( 'revision',
3089 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3090 array( 'rev_page' => $current->getPage(),
3091 "rev_user != {$user} OR rev_user_text != {$user_text}"
3093 array( 'USE INDEX' => 'page_timestamp',
3094 'ORDER BY' => 'rev_timestamp DESC' )
3096 if ( $s === false ) {
3097 # No one else ever edited this page
3098 return array( array( 'cantrollback' ) );
3099 } else if ( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
3100 # Only admins can see this text
3101 return array( array( 'notvisiblerev' ) );
3105 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3106 # Mark all reverted edits as bot
3109 if ( $wgUseRCPatrol ) {
3110 # Mark all reverted edits as patrolled
3111 $set['rc_patrolled'] = 1;
3114 if ( count( $set ) ) {
3115 $dbw->update( 'recentchanges', $set,
3117 'rc_cur_id' => $current->getPage(),
3118 'rc_user_text' => $current->getUserText(),
3119 "rc_timestamp > '{$s->rev_timestamp}'",
3124 # Generate the edit summary if necessary
3125 $target = Revision
::newFromId( $s->rev_id
);
3126 if ( empty( $summary ) ) {
3127 if ( $from == '' ) { // no public user name
3128 $summary = wfMsgForContent( 'revertpage-nouser' );
3130 $summary = wfMsgForContent( 'revertpage' );
3134 # Allow the custom summary to use the same args as the default message
3136 $target->getUserText(), $from, $s->rev_id
,
3137 $wgLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
), true ),
3138 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3140 $summary = wfMsgReplaceArgs( $summary, $args );
3143 $flags = EDIT_UPDATE
;
3145 if ( $wgUser->isAllowed( 'minoredit' ) )
3146 $flags |
= EDIT_MINOR
;
3148 if ( $bot && ( $wgUser->isAllowed( 'markbotedits' ) ||
$wgUser->isAllowed( 'bot' ) ) )
3149 $flags |
= EDIT_FORCE_BOT
;
3150 # Actually store the edit
3151 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3152 if ( !empty( $status->value
['revision'] ) ) {
3153 $revId = $status->value
['revision']->getId();
3158 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3160 $resultDetails = array(
3161 'summary' => $summary,
3162 'current' => $current,
3163 'target' => $target,
3170 * User interface for rollback operations
3172 public function rollback() {
3173 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
3176 $result = $this->doRollback(
3177 $wgRequest->getVal( 'from' ),
3178 $wgRequest->getText( 'summary' ),
3179 $wgRequest->getVal( 'token' ),
3180 $wgRequest->getBool( 'bot' ),
3184 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3185 $wgOut->rateLimited();
3188 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' ||
$result[0][0] == 'cantrollback' ) ) {
3189 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3190 $errArray = $result[0];
3191 $errMsg = array_shift( $errArray );
3192 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3193 if ( isset( $details['current'] ) ) {
3194 $current = $details['current'];
3195 if ( $current->getComment() != '' ) {
3196 $wgOut->addWikiMsgArray( 'editcomment', array(
3197 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3202 # Display permissions errors before read-only message -- there's no
3203 # point in misleading the user into thinking the inability to rollback
3204 # is only temporary.
3205 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3206 # array_diff is completely broken for arrays of arrays, sigh. Re-
3207 # move any 'readonlytext' error manually.
3209 foreach ( $result as $error ) {
3210 if ( $error != array( 'readonlytext' ) ) {
3214 $wgOut->showPermissionsErrorPage( $out );
3217 if ( $result == array( array( 'readonlytext' ) ) ) {
3218 $wgOut->readOnlyPage();
3222 $current = $details['current'];
3223 $target = $details['target'];
3224 $newId = $details['newid'];
3225 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3226 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3227 if ( $current->getUserText() === '' ) {
3228 $old = wfMsg( 'rev-deleted-user' );
3230 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3231 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3233 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3234 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3235 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3236 $wgOut->returnToMain( false, $this->mTitle
);
3238 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3239 $de = new DifferenceEngine( $this->mTitle
, $current->getId(), $newId, false, true );
3240 $de->showDiff( '', '' );
3246 * Do standard deferred updates after page view
3248 public function viewUpdates() {
3249 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3250 if ( wfReadOnly() ) {
3253 # Don't update page view counters on views from bot users (bug 14044)
3254 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3255 Article
::incViewCount( $this->getID() );
3256 $u = new SiteStatsUpdate( 1, 0, 0 );
3257 array_push( $wgDeferredUpdateList, $u );
3259 # Update newtalk / watchlist notification status
3260 $wgUser->clearNotification( $this->mTitle
);
3264 * Prepare text which is about to be saved.
3265 * Returns a stdclass with source, pst and output members
3267 public function prepareTextForEdit( $text, $revid = null ) {
3268 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid ) {
3270 return $this->mPreparedEdit
;
3273 $edit = (object)array();
3274 $edit->revid
= $revid;
3275 $edit->newText
= $text;
3276 $edit->pst
= $this->preSaveTransform( $text );
3277 $options = $this->getParserOptions();
3278 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
3279 $edit->oldText
= $this->getContent();
3280 $this->mPreparedEdit
= $edit;
3285 * Do standard deferred updates after page edit.
3286 * Update links tables, site stats, search index and message cache.
3287 * Purges pages that include this page if the text was changed here.
3288 * Every 100th edit, prune the recent changes table.
3291 * @param $text New text of the article
3292 * @param $summary Edit summary
3293 * @param $minoredit Minor edit
3294 * @param $timestamp_of_pagechange Timestamp associated with the page change
3295 * @param $newid rev_id value of the new revision
3296 * @param $changed Whether or not the content actually changed
3298 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
3299 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgEnableParserCache;
3301 wfProfileIn( __METHOD__
);
3304 # Be careful not to double-PST: $text is usually already PST-ed once
3305 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
3306 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
3307 $editInfo = $this->prepareTextForEdit( $text, $newid );
3309 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
3310 $editInfo = $this->mPreparedEdit
;
3313 # Save it to the parser cache
3314 if ( $wgEnableParserCache ) {
3315 $popts = $this->getParserOptions();
3316 $parserCache = ParserCache
::singleton();
3317 $parserCache->save( $editInfo->output
, $this, $popts );
3320 # Update the links tables
3321 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
3324 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3326 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3327 if ( 0 == mt_rand( 0, 99 ) ) {
3328 // Flush old entries from the `recentchanges` table; we do this on
3329 // random requests so as to avoid an increase in writes for no good reason
3331 $dbw = wfGetDB( DB_MASTER
);
3332 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3333 $recentchanges = $dbw->tableName( 'recentchanges' );
3334 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
3335 $dbw->query( $sql );
3339 $id = $this->getID();
3340 $title = $this->mTitle
->getPrefixedDBkey();
3341 $shortTitle = $this->mTitle
->getDBkey();
3344 wfProfileOut( __METHOD__
);
3348 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
3349 array_push( $wgDeferredUpdateList, $u );
3350 $u = new SearchUpdate( $id, $title, $text );
3351 array_push( $wgDeferredUpdateList, $u );
3353 # If this is another user's talk page, update newtalk
3354 # Don't do this if $changed = false otherwise some idiot can null-edit a
3355 # load of user talk pages and piss people off, nor if it's a minor edit
3356 # by a properly-flagged bot.
3357 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
3358 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
3359 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3360 $other = User
::newFromName( $shortTitle, false );
3362 wfDebug( __METHOD__
. ": invalid username\n" );
3363 } elseif ( User
::isIP( $shortTitle ) ) {
3364 // An anonymous user
3365 $other->setNewtalk( true );
3366 } elseif ( $other->isLoggedIn() ) {
3367 $other->setNewtalk( true );
3369 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
3374 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3375 $wgMessageCache->replace( $shortTitle, $text );
3378 wfProfileOut( __METHOD__
);
3382 * Perform article updates on a special page creation.
3384 * @param $rev Revision object
3386 * @todo This is a shitty interface function. Kill it and replace the
3387 * other shitty functions like editUpdates and such so it's not needed
3390 public function createUpdates( $rev ) {
3391 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
3392 $this->mTotalAdjustment
= 1;
3393 $this->editUpdates( $rev->getText(), $rev->getComment(),
3394 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3398 * Generate the navigation links when browsing through an article revisions
3399 * It shows the information as:
3400 * Revision as of \<date\>; view current revision
3401 * \<- Previous version | Next Version -\>
3403 * @param $oldid String: revision ID of this article revision
3405 public function setOldSubtitle( $oldid = 0 ) {
3406 global $wgLang, $wgOut, $wgUser, $wgRequest;
3408 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3412 $unhide = $wgRequest->getInt( 'unhide' ) == 1 &&
3413 $wgUser->matchEditToken( $wgRequest->getVal( 'token' ), $oldid );
3414 # Cascade unhide param in links for easy deletion browsing
3415 $extraParams = array();
3416 if ( $wgRequest->getVal( 'unhide' ) ) {
3417 $extraParams['unhide'] = 1;
3419 $revision = Revision
::newFromId( $oldid );
3421 $current = ( $oldid == $this->mLatest
);
3422 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
3423 $tddate = $wgLang->date( $this->mTimestamp
, true );
3424 $tdtime = $wgLang->time( $this->mTimestamp
, true );
3425 $sk = $wgUser->getSkin();
3427 ?
wfMsgHtml( 'currentrevisionlink' )
3430 wfMsgHtml( 'currentrevisionlink' ),
3433 array( 'known', 'noclasses' )
3436 ?
wfMsgHtml( 'diff' )
3439 wfMsgHtml( 'diff' ),
3445 array( 'known', 'noclasses' )
3447 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
3451 wfMsgHtml( 'previousrevision' ),
3454 'direction' => 'prev',
3457 array( 'known', 'noclasses' )
3459 : wfMsgHtml( 'previousrevision' );
3463 wfMsgHtml( 'diff' ),
3469 array( 'known', 'noclasses' )
3471 : wfMsgHtml( 'diff' );
3472 $nextlink = $current
3473 ?
wfMsgHtml( 'nextrevision' )
3476 wfMsgHtml( 'nextrevision' ),
3479 'direction' => 'next',
3482 array( 'known', 'noclasses' )
3484 $nextdiff = $current
3485 ?
wfMsgHtml( 'diff' )
3488 wfMsgHtml( 'diff' ),
3494 array( 'known', 'noclasses' )
3498 // User can delete revisions or view deleted revisions...
3499 $canHide = $wgUser->isAllowed( 'deleterevision' );
3500 if ( $canHide ||
( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3501 if ( !$revision->userCan( Revision
::DELETED_RESTRICTED
) ) {
3502 $cdel = $sk->revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3505 'type' => 'revision',
3506 'target' => $this->mTitle
->getPrefixedDbkey(),
3509 $cdel = $sk->revDeleteLink( $query, $revision->isDeleted( File
::DELETED_RESTRICTED
), $canHide );
3514 # Show user links if allowed to see them. If hidden, then show them only if requested...
3515 $userlinks = $sk->revUserTools( $revision, !$unhide );
3517 $m = wfMsg( 'revision-info-current' );
3518 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3519 ?
'revision-info-current'
3522 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3525 array( 'parseinline', 'replaceafter' ),
3531 $revision->getUser()
3534 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3535 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3536 $wgOut->setSubtitle( $r );
3540 * This function is called right before saving the wikitext,
3541 * so we can do things like signatures and links-in-context.
3543 * @param $text String
3545 public function preSaveTransform( $text ) {
3546 global $wgParser, $wgUser;
3547 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
3550 /* Caching functions */
3553 * checkLastModified returns true if it has taken care of all
3554 * output to the client that is necessary for this request.
3555 * (that is, it has sent a cached version of the page)
3557 protected function tryFileCache() {
3558 static $called = false;
3560 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3564 if ( $this->isFileCacheable() ) {
3565 $cache = new HTMLFileCache( $this->mTitle
);
3566 if ( $cache->isFileCacheGood( $this->mTouched
) ) {
3567 wfDebug( "Article::tryFileCache(): about to load file\n" );
3568 $cache->loadFromFileCache();
3571 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3572 ob_start( array( &$cache, 'saveToFileCache' ) );
3575 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3581 * Check if the page can be cached
3584 public function isFileCacheable() {
3586 if ( HTMLFileCache
::useFileCache() ) {
3587 $cacheable = $this->getID() && !$this->mRedirectedFrom
;
3588 // Extension may have reason to disable file caching on some pages.
3590 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3597 * Loads page_touched and returns a value indicating if it should be used
3600 public function checkTouched() {
3601 if ( !$this->mDataLoaded
) {
3602 $this->loadPageData();
3604 return !$this->mIsRedirect
;
3608 * Get the page_touched field
3610 public function getTouched() {
3611 # Ensure that page data has been loaded
3612 if ( !$this->mDataLoaded
) {
3613 $this->loadPageData();
3615 return $this->mTouched
;
3619 * Get the page_latest field
3621 public function getLatest() {
3622 if ( !$this->mDataLoaded
) {
3623 $this->loadPageData();
3625 return (int)$this->mLatest
;
3629 * Edit an article without doing all that other stuff
3630 * The article must already exist; link tables etc
3631 * are not updated, caches are not flushed.
3633 * @param $text String: text submitted
3634 * @param $comment String: comment submitted
3635 * @param $minor Boolean: whereas it's a minor modification
3637 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3638 wfProfileIn( __METHOD__
);
3640 $dbw = wfGetDB( DB_MASTER
);
3641 $revision = new Revision( array(
3642 'page' => $this->getId(),
3644 'comment' => $comment,
3645 'minor_edit' => $minor ?
1 : 0,
3647 $revision->insertOn( $dbw );
3648 $this->updateRevisionOn( $dbw, $revision );
3650 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
3652 wfProfileOut( __METHOD__
);
3656 * Used to increment the view counter
3658 * @param $id Integer: article id
3660 public static function incViewCount( $id ) {
3661 $id = intval( $id );
3662 global $wgHitcounterUpdateFreq;
3664 $dbw = wfGetDB( DB_MASTER
);
3665 $pageTable = $dbw->tableName( 'page' );
3666 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3667 $acchitsTable = $dbw->tableName( 'acchits' );
3669 if ( $wgHitcounterUpdateFreq <= 1 ) {
3670 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3674 # Not important enough to warrant an error page in case of failure
3675 $oldignore = $dbw->ignoreErrors( true );
3677 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3679 $checkfreq = intval( $wgHitcounterUpdateFreq / 25 +
1 );
3680 if ( ( rand() %
$checkfreq != 0 ) or ( $dbw->lastErrno() != 0 ) ) {
3681 # Most of the time (or on SQL errors), skip row count check
3682 $dbw->ignoreErrors( $oldignore );
3686 $res = $dbw->query( "SELECT COUNT(*) as n FROM $hitcounterTable" );
3687 $row = $dbw->fetchObject( $res );
3688 $rown = intval( $row->n
);
3689 if ( $rown >= $wgHitcounterUpdateFreq ) {
3690 wfProfileIn( 'Article::incViewCount-collect' );
3691 $old_user_abort = ignore_user_abort( true );
3693 $dbType = $dbw->getType();
3694 $dbw->lockTables( array(), array( 'hitcounter' ), __METHOD__
, false );
3695 $tabletype = $dbType == 'mysql' ?
"ENGINE=HEAP " : '';
3696 $dbw->query( "CREATE TEMPORARY TABLE $acchitsTable $tabletype AS " .
3697 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable " .
3698 'GROUP BY hc_id', __METHOD__
);
3699 $dbw->delete( 'hitcounter', '*', __METHOD__
);
3700 $dbw->unlockTables( __METHOD__
);
3701 if ( $dbType == 'mysql' ) {
3702 $dbw->query( "UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n " .
3703 'WHERE page_id = hc_id', __METHOD__
);
3706 $dbw->query( "UPDATE $pageTable SET page_counter=page_counter + hc_n " .
3707 "FROM $acchitsTable WHERE page_id = hc_id", __METHOD__
);
3709 $dbw->query( "DROP TABLE $acchitsTable", __METHOD__
);
3711 ignore_user_abort( $old_user_abort );
3712 wfProfileOut( 'Article::incViewCount-collect' );
3714 $dbw->ignoreErrors( $oldignore );
3718 * The onArticle*() functions are supposed to be a kind of hooks
3719 * which should be called whenever any of the specified actions
3722 * This is a good place to put code to clear caches, for instance.
3724 * This is called on page move and undelete, as well as edit
3726 * @param $title a title object
3728 public static function onArticleCreate( $title ) {
3729 # Update existence markers on article/talk tabs...
3730 if ( $title->isTalkPage() ) {
3731 $other = $title->getSubjectPage();
3733 $other = $title->getTalkPage();
3735 $other->invalidateCache();
3736 $other->purgeSquid();
3738 $title->touchLinks();
3739 $title->purgeSquid();
3740 $title->deleteTitleProtection();
3743 public static function onArticleDelete( $title ) {
3744 global $wgMessageCache;
3745 # Update existence markers on article/talk tabs...
3746 if ( $title->isTalkPage() ) {
3747 $other = $title->getSubjectPage();
3749 $other = $title->getTalkPage();
3751 $other->invalidateCache();
3752 $other->purgeSquid();
3754 $title->touchLinks();
3755 $title->purgeSquid();
3758 HTMLFileCache
::clearFileCache( $title );
3761 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3762 $wgMessageCache->replace( $title->getDBkey(), false );
3765 if ( $title->getNamespace() == NS_FILE
) {
3766 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3767 $update->doUpdate();
3770 if ( $title->getNamespace() == NS_USER_TALK
) {
3771 $user = User
::newFromName( $title->getText(), false );
3772 $user->setNewtalk( false );
3775 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3779 * Purge caches on page update etc
3781 public static function onArticleEdit( $title, $flags = '' ) {
3782 global $wgDeferredUpdateList;
3784 // Invalidate caches of articles which include this page
3785 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3787 // Invalidate the caches of all pages which redirect here
3788 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3790 # Purge squid for this page only
3791 $title->purgeSquid();
3793 # Clear file cache for this page only
3794 HTMLFileCache
::clearFileCache( $title );
3800 * Overriden by ImagePage class, only present here to avoid a fatal error
3801 * Called for ?action=revert
3803 public function revert() {
3805 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3809 * Info about this page
3810 * Called for ?action=info when $wgAllowPageInfo is on.
3812 public function info() {
3813 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3815 if ( !$wgAllowPageInfo ) {
3816 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3820 $page = $this->mTitle
->getSubjectPage();
3822 $wgOut->setPagetitle( $page->getPrefixedText() );
3823 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3824 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3826 if ( !$this->mTitle
->exists() ) {
3827 $wgOut->addHTML( '<div class="noarticletext">' );
3828 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3829 // This doesn't quite make sense; the user is asking for
3830 // information about the _page_, not the message... -- RC
3831 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3833 $msg = $wgUser->isLoggedIn()
3835 : 'noarticletextanon';
3836 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3838 $wgOut->addHTML( '</div>' );
3840 $dbr = wfGetDB( DB_SLAVE
);
3842 'wl_title' => $page->getDBkey(),
3843 'wl_namespace' => $page->getNamespace() );
3844 $numwatchers = $dbr->selectField(
3849 $this->getSelectOptions() );
3851 $pageInfo = $this->pageCountInfo( $page );
3852 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3854 $wgOut->addHTML( "<ul><li>" . wfMsg( "numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3855 $wgOut->addHTML( "<li>" . wfMsg( 'numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>' );
3857 $wgOut->addHTML( '<li>' . wfMsg( "numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>' );
3859 $wgOut->addHTML( '<li>' . wfMsg( "numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3861 $wgOut->addHTML( '<li>' . wfMsg( 'numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3863 $wgOut->addHTML( '</ul>' );
3868 * Return the total number of edits and number of unique editors
3869 * on a given page. If page does not exist, returns false.
3871 * @param $title Title object
3874 public function pageCountInfo( $title ) {
3875 $id = $title->getArticleId();
3879 $dbr = wfGetDB( DB_SLAVE
);
3880 $rev_clause = array( 'rev_page' => $id );
3881 $edits = $dbr->selectField(
3886 $this->getSelectOptions()
3888 $authors = $dbr->selectField(
3890 'COUNT(DISTINCT rev_user_text)',
3893 $this->getSelectOptions()
3895 return array( 'edits' => $edits, 'authors' => $authors );
3899 * Return a list of templates used by this article.
3900 * Uses the templatelinks table
3902 * @return Array of Title objects
3904 public function getUsedTemplates() {
3906 $id = $this->mTitle
->getArticleID();
3910 $dbr = wfGetDB( DB_SLAVE
);
3911 $res = $dbr->select( array( 'templatelinks' ),
3912 array( 'tl_namespace', 'tl_title' ),
3913 array( 'tl_from' => $id ),
3915 if ( $res !== false ) {
3916 foreach ( $res as $row ) {
3917 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3920 $dbr->freeResult( $res );
3925 * Returns a list of hidden categories this page is a member of.
3926 * Uses the page_props and categorylinks tables.
3928 * @return Array of Title objects
3930 public function getHiddenCategories() {
3932 $id = $this->mTitle
->getArticleID();
3936 $dbr = wfGetDB( DB_SLAVE
);
3937 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3939 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3940 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
3942 if ( $res !== false ) {
3943 foreach ( $res as $row ) {
3944 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3947 $dbr->freeResult( $res );
3952 * Return an applicable autosummary if one exists for the given edit.
3953 * @param $oldtext String: the previous text of the page.
3954 * @param $newtext String: The submitted text of the page.
3955 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3956 * @return string An appropriate autosummary, or an empty string.
3958 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3959 # Decide what kind of autosummary is needed.
3961 # Redirect autosummaries
3962 $ot = Title
::newFromRedirect( $oldtext );
3963 $rt = Title
::newFromRedirect( $newtext );
3964 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
3965 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3968 # New page autosummaries
3969 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
3970 # If they're making a new article, give its text, truncated, in the summary.
3972 $truncatedtext = $wgContLang->truncate(
3973 str_replace( "\n", ' ', $newtext ),
3974 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
3975 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3978 # Blanking autosummaries
3979 if ( $oldtext != '' && $newtext == '' ) {
3980 return wfMsgForContent( 'autosumm-blank' );
3981 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
3982 # Removing more than 90% of the article
3984 $truncatedtext = $wgContLang->truncate(
3986 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
3987 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3990 # If we reach this point, there's no applicable autosummary for our case, so our
3991 # autosummary is empty.
3996 * Add the primary page-view wikitext to the output buffer
3997 * Saves the text into the parser cache if possible.
3998 * Updates templatelinks if it is out of date.
4000 * @param $text String
4001 * @param $cache Boolean
4003 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4006 $this->mParserOutput
= $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4007 $wgOut->addParserOutput( $this->mParserOutput
);
4011 * This does all the heavy lifting for outputWikitext, except it returns the parser
4012 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4013 * say, embedding thread pages within a discussion system (LiquidThreads)
4015 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4016 global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
4018 if ( !$parserOptions ) {
4019 $parserOptions = $this->getParserOptions();
4023 $this->mParserOutput
= $wgParser->parse( $text, $this->mTitle
,
4024 $parserOptions, true, true, $this->getRevIdFetched() );
4029 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4030 $this->mTitle
->getPrefixedDBkey() ) );
4033 if ( $wgEnableParserCache && $cache && $this && $this->mParserOutput
->getCacheTime() != -1 ) {
4034 $parserCache = ParserCache
::singleton();
4035 $parserCache->save( $this->mParserOutput
, $this, $parserOptions );
4037 // Make sure file cache is not used on uncacheable content.
4038 // Output that has magic words in it can still use the parser cache
4039 // (if enabled), though it will generally expire sooner.
4040 if ( $this->mParserOutput
->getCacheTime() == -1 ||
$this->mParserOutput
->containsOldMagic() ) {
4041 $wgUseFileCache = false;
4043 $this->doCascadeProtectionUpdates( $this->mParserOutput
);
4044 return $this->mParserOutput
;
4048 * Get parser options suitable for rendering the primary article wikitext
4050 public function getParserOptions() {
4052 if ( !$this->mParserOptions
) {
4053 $this->mParserOptions
= new ParserOptions( $wgUser );
4054 $this->mParserOptions
->setTidy( true );
4055 $this->mParserOptions
->enableLimitReport();
4057 return $this->mParserOptions
;
4060 protected function doCascadeProtectionUpdates( $parserOutput ) {
4061 if ( !$this->isCurrent() ||
wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
4065 // templatelinks table may have become out of sync,
4066 // especially if using variable-based transclusions.
4067 // For paranoia, check if things have changed and if
4068 // so apply updates to the database. This will ensure
4069 // that cascaded protections apply as soon as the changes
4072 # Get templates from templatelinks
4073 $id = $this->mTitle
->getArticleID();
4075 $tlTemplates = array();
4077 $dbr = wfGetDB( DB_SLAVE
);
4078 $res = $dbr->select( array( 'templatelinks' ),
4079 array( 'tl_namespace', 'tl_title' ),
4080 array( 'tl_from' => $id ),
4084 foreach ( $res as $row ) {
4085 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4088 # Get templates from parser output.
4089 $poTemplates = array();
4090 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4091 foreach ( $templates as $dbk => $id ) {
4092 $poTemplates["$ns:$dbk"] = true;
4097 # Note that we simulate array_diff_key in PHP <5.0.x
4098 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4100 if ( count( $templates_diff ) > 0 ) {
4101 # Whee, link updates time.
4102 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
4108 * Update all the appropriate counts in the category table, given that
4109 * we've added the categories $added and deleted the categories $deleted.
4111 * @param $added array The names of categories that were added
4112 * @param $deleted array The names of categories that were deleted
4115 public function updateCategoryCounts( $added, $deleted ) {
4116 $ns = $this->mTitle
->getNamespace();
4117 $dbw = wfGetDB( DB_MASTER
);
4119 # First make sure the rows exist. If one of the "deleted" ones didn't
4120 # exist, we might legitimately not create it, but it's simpler to just
4121 # create it and then give it a negative value, since the value is bogus
4124 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4125 $insertCats = array_merge( $added, $deleted );
4126 if ( !$insertCats ) {
4127 # Okay, nothing to do
4130 $insertRows = array();
4131 foreach ( $insertCats as $cat ) {
4132 $insertRows[] = array(
4133 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4137 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
4139 $addFields = array( 'cat_pages = cat_pages + 1' );
4140 $removeFields = array( 'cat_pages = cat_pages - 1' );
4141 if ( $ns == NS_CATEGORY
) {
4142 $addFields[] = 'cat_subcats = cat_subcats + 1';
4143 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4144 } elseif ( $ns == NS_FILE
) {
4145 $addFields[] = 'cat_files = cat_files + 1';
4146 $removeFields[] = 'cat_files = cat_files - 1';
4153 array( 'cat_title' => $added ),
4161 array( 'cat_title' => $deleted ),
4167 /** Lightweight method to get the parser output for a page, checking the parser cache
4168 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4169 * consider, so it's not appropriate to use there.
4171 function getParserOutput( $oldid = null ) {
4172 global $wgEnableParserCache, $wgUser, $wgOut;
4174 // Should the parser cache be used?
4175 $useParserCache = $wgEnableParserCache &&
4176 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
4180 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
4181 if ( $wgUser->getOption( 'stubthreshold' ) ) {
4182 wfIncrStats( 'pcache_miss_stub' );
4185 $parserOutput = false;
4186 if ( $useParserCache ) {
4187 $parserOutput = ParserCache
::singleton()->get( $this, $this->getParserOptions() );
4190 if ( $parserOutput === false ) {
4191 // Cache miss; parse and output it.
4192 $rev = Revision
::newFromTitle( $this->getTitle(), $oldid );
4194 return $this->getOutputFromWikitext( $rev->getText(), $useParserCache );
4196 return $parserOutput;